JSResourceEditor.cpp 16 KB

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