JSResourceEditor.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. //
  2. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  3. // LICENSE: Atomic Game Engine Editor and Tools EULA
  4. // Please see LICENSE_ATOMIC_EDITOR_AND_TOOLS.md in repository root for
  5. // license information: https://github.com/AtomicGameEngine/AtomicGameEngine
  6. //
  7. #include <Atomic/Container/ArrayPtr.h>
  8. #include <Atomic/UI/UI.h>
  9. #include <Atomic/IO/Log.h>
  10. #include <Atomic/IO/File.h>
  11. #include <Atomic/IO/FileSystem.h>
  12. #include <Atomic/Resource/ResourceCache.h>
  13. #include <Atomic/Core/CoreEvents.h>
  14. #include <AtomicJS/Javascript/JSVM.h>
  15. #include "JSResourceEditor.h"
  16. #include "../Javascript/JSAutocomplete.h"
  17. #include "../Javascript/JSTheme.h"
  18. #include "../Javascript/JSASTSyntaxColorVisitor.h"
  19. #include <TurboBadger/tb_message_window.h>
  20. #include <TurboBadger/tb_editfield.h>
  21. #include <TurboBadger/tb_style_edit.h>
  22. #include <TurboBadger/tb_style_edit_content.h>
  23. using namespace tb;
  24. namespace AtomicEditor
  25. {
  26. JSResourceEditor ::JSResourceEditor(Context* context, const String &fullpath, UITabContainer *container) :
  27. ResourceEditor(context, fullpath, container),
  28. styleEdit_(0),
  29. lineNumberList_(0),
  30. editField_(0),
  31. autocomplete_(0),
  32. textDirty_(true),
  33. textDelta_(0.0f),
  34. currentFindPos_(-1)
  35. {
  36. TBLayout* layout = new TBLayout();
  37. layout->SetLayoutSize(LAYOUT_SIZE_GRAVITY);
  38. layout->SetGravity(WIDGET_GRAVITY_ALL);
  39. layout->SetLayoutDistribution(LAYOUT_DISTRIBUTION_GRAVITY);
  40. rootContentWidget_->GetInternalWidget()->AddChild(layout);
  41. TBContainer* c = new TBContainer();
  42. c->SetGravity(WIDGET_GRAVITY_ALL);
  43. TBEditField* text = editField_ = new TBEditField();
  44. text->SetMultiline(true);
  45. text->SetWrapping(true);
  46. text->SetGravity(WIDGET_GRAVITY_ALL);
  47. text->SetStyling(true);
  48. text->SetSkinBg(TBIDC("TextCode"));
  49. TBFontDescription fd;
  50. fd.SetID(TBIDC("Monaco"));
  51. fd.SetSize(12);
  52. text->SetFontDescription(fd);
  53. SharedPtr<File> jsFile(GetSubsystem<ResourceCache>()->GetFile(fullpath));
  54. assert(jsFile);
  55. String source;
  56. jsFile->ReadText(source);
  57. String json;
  58. JSASTProgram* program = NULL;
  59. if (ParseJavascriptToJSON(source.CString(), json))
  60. {
  61. program = JSASTProgram::ParseFromJSON(fullpath, json);
  62. }
  63. text->SetText(source.CString());
  64. lineNumberList_ = new TBSelectList();
  65. lineNumberList_->SetFontDescription(fd);
  66. lineNumberList_->SetSkinBg(TBIDC("LineNumberSelectList"));
  67. lineNumberList_->GetScrollContainer()->SetScrollMode(SCROLL_MODE_OFF);
  68. //lineNumberList_->GetScrollContainer()->SetIgnoreScrollEvents(true);
  69. lineNumberList_->SetGravity(WIDGET_GRAVITY_ALL);
  70. LayoutParams lp;
  71. lp.max_w = 48;
  72. lineNumberList_->SetLayoutParams(lp);
  73. c->AddChild(text);
  74. layout->AddChild(lineNumberList_);
  75. layout->AddChild(c);
  76. layout->SetSpacing(0);
  77. TBStyleEdit* sedit = text->GetStyleEdit();
  78. TBTextTheme* theme = new TBTextTheme();
  79. for (unsigned i = 0; i < TB_MAX_TEXT_THEME_COLORS; i++)
  80. theme->themeColors[i] = TBColor(255, 255, 255);
  81. theme->themeColors[JSTHEME_LITERAL_STRING].SetFromString("#E6DB74", 7);
  82. theme->themeColors[JSTHEME_LITERAL_NUMBER].SetFromString("#AE81FF", 7);
  83. theme->themeColors[JSTHEME_LITERAL_REGEX].SetFromString("#AE81FF", 7);
  84. theme->themeColors[JSTHEME_LITERAL_BOOLEAN].SetFromString("#AE81FF", 7);
  85. theme->themeColors[JSTHEME_LITERAL_NULL].SetFromString("#AE81FF", 7);
  86. theme->themeColors[JSTHEME_FUNCTION].SetFromString("#66D9EF", 7);
  87. theme->themeColors[JSTHEME_VAR].SetFromString("#66D9EF", 7);
  88. theme->themeColors[JSTHEME_KEYWORD].SetFromString("#f92672", 7);
  89. theme->themeColors[JSTHEME_OPERATOR].SetFromString("#f92672", 7);
  90. theme->themeColors[JSTHEME_CODE].SetFromString("#a6e22e", 7);
  91. theme->themeColors[JSTHEME_COMMENT].SetFromString("#75715e", 7);
  92. theme->themeColors[JSTHEME_FUNCTIONDECLARG].SetFromString("#FF9800", 7);
  93. sedit->SetTextTheme(theme);
  94. sedit->text_change_listener = this;
  95. styleEdit_ = sedit;
  96. UpdateLineNumbers();
  97. if (program)
  98. {
  99. JSASTSyntaxColorVisitor syntaxColor(sedit);
  100. syntaxColor.visit(program);
  101. }
  102. autocomplete_ = new JSAutocomplete(text);
  103. autocomplete_->UpdateLocals();
  104. SubscribeToEvent(E_UPDATE, HANDLER(JSResourceEditor, HandleUpdate));
  105. // FIXME: Set the size at the end of setup, so all children are updated accordingly
  106. // future size changes will be handled automatically
  107. IntRect rect = container_->GetContentRoot()->GetRect();
  108. rootContentWidget_->SetSize(rect.Width(), rect.Height());
  109. }
  110. JSResourceEditor::~JSResourceEditor()
  111. {
  112. }
  113. void JSResourceEditor::FormatCode()
  114. {
  115. TBStr text;
  116. styleEdit_->GetText(text);
  117. if (text.Length())
  118. {
  119. String output;
  120. if (BeautifyJavascript(text.CStr(), output))
  121. {
  122. if (output.Length())
  123. {
  124. styleEdit_->selection.SelectAll();
  125. styleEdit_->InsertText(output.CString(), output.Length());
  126. }
  127. }
  128. }
  129. }
  130. void JSResourceEditor::UpdateLineNumbers()
  131. {
  132. if (!styleEdit_)
  133. return;
  134. TBGenericStringItemSource* lineSource = lineNumberList_->GetDefaultSource();
  135. int lines = lineSource->GetNumItems();
  136. int lineCount = styleEdit_->blocks.CountLinks();
  137. if (lines == lineCount)
  138. return;
  139. while (lines > lineCount)
  140. {
  141. lineSource->DeleteItem(lineSource->GetNumItems() - 1);
  142. lines --;
  143. }
  144. for (int i = lines; i < lineCount; i++)
  145. {
  146. String sline;
  147. sline.AppendWithFormat("%i ", i + 1);
  148. TBGenericStringItem* item = new TBGenericStringItem(sline.CString());
  149. lineSource->AddItem(item);
  150. }
  151. // item widgets don't exist until ValidateList
  152. lineNumberList_->ValidateList();
  153. for (int i = 0; i < lineCount; i++)
  154. {
  155. TBTextField* textField = (TBTextField* )lineNumberList_->GetItemWidget(i);
  156. if (textField)
  157. {
  158. textField->SetTextAlign(TB_TEXT_ALIGN_RIGHT);
  159. textField->SetSkinBg(TBIDC("TBSelectItemLineNumber"));
  160. }
  161. }
  162. }
  163. void JSResourceEditor::OnChange(TBStyleEdit* styleEdit)
  164. {
  165. textDelta_ = 0.25f;
  166. textDirty_ = true;
  167. modified_ = true;
  168. String filename = GetFileNameAndExtension(fullpath_);
  169. filename += "*";
  170. button_->SetText(filename.CString());
  171. autocomplete_->Hide();
  172. TBTextFragment* fragment = 0;
  173. int ofs = styleEdit_->caret.pos.ofs;
  174. fragment = styleEdit_->caret.pos.block->FindFragment(ofs, true);
  175. if (fragment && fragment->len && (styleEdit_->caret.pos.ofs == (fragment->ofs + fragment->len)))
  176. {
  177. String value(fragment->Str(), fragment->len);
  178. bool hasCompletions = autocomplete_->UpdateCompletions(value);
  179. if (hasCompletions)
  180. {
  181. autocomplete_->SetPosition(TBPoint(fragment->xpos, (styleEdit_->caret.y - styleEdit_->scroll_y) + fragment->line_height));
  182. // autocomplete disabled until it can be looked at
  183. //autocomplete_->Show();
  184. }
  185. }
  186. UpdateLineNumbers();
  187. }
  188. bool JSResourceEditor::OnEvent(const TBWidgetEvent &ev)
  189. {
  190. if (ev.type == EVENT_TYPE_KEY_DOWN)
  191. {
  192. if (autocomplete_ && autocomplete_->Visible())
  193. {
  194. return autocomplete_->OnEvent(ev);
  195. }
  196. if (ev.special_key == TB_KEY_ESC)
  197. {
  198. //SendEvent(E_FINDTEXTCLOSE);
  199. }
  200. }
  201. if (ev.type == EVENT_TYPE_SHORTCUT)
  202. {
  203. if (ev.ref_id == TBIDC("close"))
  204. {
  205. RequestClose();
  206. }
  207. if (ev.ref_id == TBIDC("find"))
  208. {
  209. //using namespace FindTextOpen;
  210. //SendEvent(E_FINDTEXTOPEN);
  211. }
  212. else if (ev.ref_id == TBIDC("findnext") || ev.ref_id == TBIDC("findprev"))
  213. {
  214. /*
  215. String text;
  216. FindTextWidget* finder = GetSubsystem<FindTextWidget>();
  217. finder->GetFindText(text);
  218. // TODO: get flags from finder
  219. unsigned flags = FINDTEXT_FLAG_NONE;
  220. if (ev.ref_id == TBIDC("findnext"))
  221. flags |= FINDTEXT_FLAG_NEXT;
  222. else if (ev.ref_id == TBIDC("findprev"))
  223. flags |= FINDTEXT_FLAG_PREV;
  224. flags |= FINDTEXT_FLAG_WRAP;
  225. finder->Find(text, flags);
  226. */
  227. }
  228. else if (ev.ref_id == TBIDC("cut") || ev.ref_id == TBIDC("copy") || ev.ref_id == TBIDC("paste")
  229. || ev.ref_id == TBIDC("selectall") || ev.ref_id == TBIDC("undo") || ev.ref_id == TBIDC("redo") )
  230. {
  231. editField_->OnEvent(ev);
  232. }
  233. }
  234. return false;
  235. }
  236. void JSResourceEditor::HandleUpdate(StringHash eventType, VariantMap& eventData)
  237. {
  238. if (!styleEdit_)
  239. return;
  240. // sync line number
  241. lineNumberList_->GetScrollContainer()->ScrollTo(0, styleEdit_->scroll_y);
  242. lineNumberList_->SetValue(styleEdit_->GetCaretLine());
  243. if (autocomplete_->Visible())
  244. {
  245. TBTextFragment* fragment = 0;
  246. int ofs = styleEdit_->caret.pos.ofs;
  247. fragment = styleEdit_->caret.pos.block->FindFragment(ofs, true);
  248. if (fragment && (styleEdit_->caret.pos.ofs == (fragment->ofs + fragment->len)))
  249. {
  250. String value(fragment->Str(), fragment->len);
  251. bool hasCompletions = autocomplete_->UpdateCompletions(value);
  252. if (!hasCompletions)
  253. {
  254. autocomplete_->Hide();
  255. }
  256. }
  257. }
  258. // Timestep parameter is same no matter what event is being listened to
  259. float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
  260. if (!textDirty_)
  261. return;
  262. if (textDelta_ > 0.0f)
  263. {
  264. textDelta_ -= timeStep;
  265. if (textDelta_ < 0.0f)
  266. {
  267. textDelta_ = 0.0f;
  268. }
  269. else
  270. {
  271. return;
  272. }
  273. }
  274. TBStr text;
  275. styleEdit_->GetText(text);
  276. JSASTProgram* program = NULL;
  277. String json;
  278. if (ParseJavascriptToJSON(text.CStr(), json))
  279. {
  280. program = JSASTProgram::ParseFromJSON("fullpath", json);
  281. if (program)
  282. {
  283. JSASTSyntaxColorVisitor syntaxColor(styleEdit_);
  284. syntaxColor.visit(program);
  285. delete program;
  286. }
  287. }
  288. textDirty_ = false;
  289. editField_->SetFocus(WIDGET_FOCUS_REASON_UNKNOWN);
  290. }
  291. void JSResourceEditor::FindTextClose()
  292. {
  293. editField_->SetFocus(WIDGET_FOCUS_REASON_UNKNOWN);
  294. styleEdit_->selection.SelectNothing();
  295. }
  296. bool JSResourceEditor::FindText(const String& findText, unsigned flags)
  297. {
  298. /*
  299. unsigned findLength = findText.Length();
  300. if (!findLength)
  301. return true;
  302. TBStr _source;
  303. styleEdit_->GetText(_source);
  304. String source = _source.CStr();
  305. unsigned pos = String::NPOS;
  306. int startPos = currentFindPos_;
  307. if (currentFindPos_ == -1)
  308. startPos = styleEdit_->caret.GetGlobalOfs();
  309. else
  310. {
  311. if (flags & FINDTEXT_FLAG_NEXT)
  312. startPos += findLength;
  313. }
  314. if (flags & FINDTEXT_FLAG_PREV)
  315. {
  316. String pretext = source.Substring(0, startPos);
  317. pos = pretext.FindLast(findText, String::NPOS, flags & FINDTEXT_FLAG_CASESENSITIVE ? true : false);
  318. }
  319. else
  320. {
  321. pos = source.Find(findText, startPos, flags & FINDTEXT_FLAG_CASESENSITIVE ? true : false);
  322. }
  323. if (pos == String::NPOS)
  324. {
  325. if (flags & FINDTEXT_FLAG_WRAP)
  326. {
  327. if (flags & FINDTEXT_FLAG_PREV)
  328. {
  329. pos = source.FindLast(findText, String::NPOS, flags & FINDTEXT_FLAG_CASESENSITIVE ? true : false);
  330. }
  331. else
  332. {
  333. pos = source.Find(findText, 0, flags & FINDTEXT_FLAG_CASESENSITIVE ? true : false);
  334. }
  335. }
  336. if (pos == String::NPOS)
  337. {
  338. styleEdit_->selection.SelectNothing();
  339. return true;
  340. }
  341. }
  342. currentFindPos_ = pos;
  343. styleEdit_->caret.SetGlobalOfs((int) pos + findLength);
  344. int height = styleEdit_->layout_height;
  345. int newy = styleEdit_->caret.y - height/2;
  346. styleEdit_->SetScrollPos(styleEdit_->scroll_x, newy);
  347. styleEdit_->selection.Select(pos, pos + findLength);
  348. */
  349. return true;
  350. }
  351. void JSResourceEditor::SetFocus()
  352. {
  353. editField_->SetFocus(WIDGET_FOCUS_REASON_UNKNOWN);
  354. }
  355. void JSResourceEditor::GotoTokenPos(int tokenPos)
  356. {
  357. styleEdit_->caret.SetGlobalOfs(tokenPos);
  358. int height = styleEdit_->layout_height;
  359. int newy = styleEdit_->caret.y - height/2;
  360. styleEdit_->SetScrollPos(styleEdit_->scroll_x, newy);
  361. }
  362. void JSResourceEditor::GotoLineNumber(int lineNumber)
  363. {
  364. int line = 0;
  365. TBBlock *block = NULL;
  366. for (block = styleEdit_->blocks.GetFirst(); block; block = block->GetNext())
  367. {
  368. if (lineNumber == line)
  369. break;
  370. line++;
  371. }
  372. if (!block)
  373. return;
  374. styleEdit_->caret.Place(block, 0);
  375. int height = styleEdit_->layout_height;
  376. int newy = styleEdit_->caret.y - height/2;
  377. styleEdit_->SetScrollPos(styleEdit_->scroll_x, newy);
  378. }
  379. bool JSResourceEditor::ParseJavascriptToJSON(const char* source, String& json, bool loose)
  380. {
  381. JSVM* vm = JSVM::GetJSVM(NULL);
  382. duk_context* ctx = vm->GetJSContext();
  383. int top = duk_get_top(ctx);
  384. json.Clear();
  385. duk_get_global_string(ctx, "require");
  386. duk_push_string(ctx, "AtomicEditor/JavaScript/Lib/jsutils");
  387. if (duk_pcall(ctx, 1))
  388. {
  389. printf("Error: %s\n", duk_safe_to_string(ctx, -1));
  390. duk_set_top(ctx, top);
  391. return false;
  392. }
  393. duk_get_prop_string(ctx, -1, "parseToJSON");
  394. duk_push_string(ctx, source);
  395. bool ok = true;
  396. if (duk_pcall(ctx, 1))
  397. {
  398. ok = false;
  399. printf("Error: %s\n", duk_safe_to_string(ctx, -1));
  400. }
  401. else
  402. {
  403. json = duk_to_string(ctx, -1);
  404. }
  405. duk_set_top(ctx, top);
  406. return ok;
  407. }
  408. bool JSResourceEditor::BeautifyJavascript(const char* source, String& output)
  409. {
  410. JSVM* vm = JSVM::GetJSVM(NULL);
  411. duk_context* ctx = vm->GetJSContext();
  412. int top = duk_get_top(ctx);
  413. output.Clear();
  414. duk_get_global_string(ctx, "require");
  415. duk_push_string(ctx, "AtomicEditor/JavaScript/Lib/jsutils");
  416. if (duk_pcall(ctx, 1))
  417. {
  418. printf("Error: %s\n", duk_safe_to_string(ctx, -1));
  419. duk_set_top(ctx, top);
  420. return false;
  421. }
  422. duk_get_prop_string(ctx, -1, "jsBeautify");
  423. duk_push_string(ctx, source);
  424. bool ok = true;
  425. if (duk_pcall(ctx, 1))
  426. {
  427. ok = false;
  428. printf("Error: %s\n", duk_safe_to_string(ctx, -1));
  429. }
  430. else
  431. {
  432. output = duk_to_string(ctx, -1);
  433. }
  434. // ignore result
  435. duk_set_top(ctx, top);
  436. return ok;
  437. }
  438. bool JSResourceEditor::Save()
  439. {
  440. if (!modified_)
  441. return true;
  442. TBStr text;
  443. styleEdit_->GetText(text);
  444. File file(context_, fullpath_, FILE_WRITE);
  445. file.Write((void*) text.CStr(), text.Length());
  446. file.Close();
  447. String filename = GetFileNameAndExtension(fullpath_);
  448. button_->SetText(filename.CString());
  449. modified_ = false;
  450. return true;
  451. }
  452. }