JSResourceEditor.cpp 15 KB

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