Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

juce_TextEditor.cpp 75KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. // a word or space that can't be broken down any further
  18. struct TextAtom
  19. {
  20. //==============================================================================
  21. String atomText;
  22. float width;
  23. int numChars;
  24. //==============================================================================
  25. bool isWhitespace() const noexcept { return CharacterFunctions::isWhitespace (atomText[0]); }
  26. bool isNewLine() const noexcept { return atomText[0] == '\r' || atomText[0] == '\n'; }
  27. String getText (const juce_wchar passwordCharacter) const
  28. {
  29. if (passwordCharacter == 0)
  30. return atomText;
  31. return String::repeatedString (String::charToString (passwordCharacter),
  32. atomText.length());
  33. }
  34. String getTrimmedText (const juce_wchar passwordCharacter) const
  35. {
  36. if (passwordCharacter == 0)
  37. return atomText.substring (0, numChars);
  38. if (isNewLine())
  39. return String::empty;
  40. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41. }
  42. };
  43. //==============================================================================
  44. // a run of text with a single font and colour
  45. class TextEditor::UniformTextSection
  46. {
  47. public:
  48. UniformTextSection (const String& text, const Font& f, const Colour col, const juce_wchar passwordChar)
  49. : font (f), colour (col)
  50. {
  51. initialiseAtoms (text, passwordChar);
  52. }
  53. UniformTextSection (const UniformTextSection& other)
  54. : font (other.font), colour (other.colour)
  55. {
  56. atoms.ensureStorageAllocated (other.atoms.size());
  57. for (int i = 0; i < other.atoms.size(); ++i)
  58. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  59. }
  60. ~UniformTextSection() {} // (no need to delete the atoms, as they're explicitly deleted by the caller)
  61. void clear()
  62. {
  63. for (int i = atoms.size(); --i >= 0;)
  64. delete atoms.getUnchecked (i);
  65. atoms.clear();
  66. }
  67. void append (const UniformTextSection& other, const juce_wchar passwordChar)
  68. {
  69. if (other.atoms.size() > 0)
  70. {
  71. int i = 0;
  72. if (TextAtom* const lastAtom = atoms.getLast())
  73. {
  74. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  75. {
  76. TextAtom* const first = other.atoms.getUnchecked(0);
  77. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  78. {
  79. lastAtom->atomText += first->atomText;
  80. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  81. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordChar));
  82. delete first;
  83. ++i;
  84. }
  85. }
  86. }
  87. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  88. while (i < other.atoms.size())
  89. {
  90. atoms.add (other.atoms.getUnchecked(i));
  91. ++i;
  92. }
  93. }
  94. }
  95. UniformTextSection* split (const int indexToBreakAt, const juce_wchar passwordChar)
  96. {
  97. UniformTextSection* const section2 = new UniformTextSection (String::empty, font, colour, passwordChar);
  98. int index = 0;
  99. for (int i = 0; i < atoms.size(); ++i)
  100. {
  101. TextAtom* const atom = atoms.getUnchecked(i);
  102. const int nextIndex = index + atom->numChars;
  103. if (index == indexToBreakAt)
  104. {
  105. for (int j = i; j < atoms.size(); ++j)
  106. section2->atoms.add (atoms.getUnchecked (j));
  107. for (int j = atoms.size(); --j >= i;)
  108. atoms.remove (j);
  109. break;
  110. }
  111. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  112. {
  113. TextAtom* const secondAtom = new TextAtom();
  114. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  115. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordChar));
  116. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  117. section2->atoms.add (secondAtom);
  118. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  119. atom->width = font.getStringWidthFloat (atom->getText (passwordChar));
  120. atom->numChars = (uint16) (indexToBreakAt - index);
  121. for (int j = i + 1; j < atoms.size(); ++j)
  122. section2->atoms.add (atoms.getUnchecked (j));
  123. for (int j = atoms.size(); --j > i;)
  124. atoms.remove (j);
  125. break;
  126. }
  127. index = nextIndex;
  128. }
  129. return section2;
  130. }
  131. void appendAllText (MemoryOutputStream& mo) const
  132. {
  133. for (int i = 0; i < atoms.size(); ++i)
  134. mo << atoms.getUnchecked(i)->atomText;
  135. }
  136. void appendSubstring (MemoryOutputStream& mo, const Range<int> range) const
  137. {
  138. int index = 0;
  139. for (int i = 0; i < atoms.size(); ++i)
  140. {
  141. const TextAtom* const atom = atoms.getUnchecked (i);
  142. const int nextIndex = index + atom->numChars;
  143. if (range.getStart() < nextIndex)
  144. {
  145. if (range.getEnd() <= index)
  146. break;
  147. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  148. if (! r.isEmpty())
  149. mo << atom->atomText.substring (r.getStart(), r.getEnd());
  150. }
  151. index = nextIndex;
  152. }
  153. }
  154. int getTotalLength() const noexcept
  155. {
  156. int total = 0;
  157. for (int i = atoms.size(); --i >= 0;)
  158. total += atoms.getUnchecked(i)->numChars;
  159. return total;
  160. }
  161. void setFont (const Font& newFont, const juce_wchar passwordChar)
  162. {
  163. if (font != newFont)
  164. {
  165. font = newFont;
  166. for (int i = atoms.size(); --i >= 0;)
  167. {
  168. TextAtom* const atom = atoms.getUnchecked(i);
  169. atom->width = newFont.getStringWidthFloat (atom->getText (passwordChar));
  170. }
  171. }
  172. }
  173. //==============================================================================
  174. Font font;
  175. Colour colour;
  176. Array <TextAtom*> atoms;
  177. private:
  178. void initialiseAtoms (const String& textToParse, const juce_wchar passwordChar)
  179. {
  180. String::CharPointerType text (textToParse.getCharPointer());
  181. while (! text.isEmpty())
  182. {
  183. size_t numChars = 0;
  184. String::CharPointerType start (text);
  185. // create a whitespace atom unless it starts with non-ws
  186. if (text.isWhitespace() && *text != '\r' && *text != '\n')
  187. {
  188. do
  189. {
  190. ++text;
  191. ++numChars;
  192. }
  193. while (text.isWhitespace() && *text != '\r' && *text != '\n');
  194. }
  195. else
  196. {
  197. if (*text == '\r')
  198. {
  199. ++text;
  200. ++numChars;
  201. if (*text == '\n')
  202. {
  203. ++start;
  204. ++text;
  205. }
  206. }
  207. else if (*text == '\n')
  208. {
  209. ++text;
  210. ++numChars;
  211. }
  212. else
  213. {
  214. while (! (text.isEmpty() || text.isWhitespace()))
  215. {
  216. ++text;
  217. ++numChars;
  218. }
  219. }
  220. }
  221. TextAtom* const atom = new TextAtom();
  222. atom->atomText = String (start, numChars);
  223. atom->width = font.getStringWidthFloat (atom->getText (passwordChar));
  224. atom->numChars = (uint16) numChars;
  225. atoms.add (atom);
  226. }
  227. }
  228. UniformTextSection& operator= (const UniformTextSection& other);
  229. JUCE_LEAK_DETECTOR (UniformTextSection)
  230. };
  231. //==============================================================================
  232. class TextEditor::Iterator
  233. {
  234. public:
  235. Iterator (const Array <UniformTextSection*>& sectionList,
  236. const float wrapWidth,
  237. const juce_wchar passwordChar)
  238. : indexInText (0),
  239. lineY (0),
  240. lineHeight (0),
  241. maxDescent (0),
  242. atomX (0),
  243. atomRight (0),
  244. atom (0),
  245. currentSection (nullptr),
  246. sections (sectionList),
  247. sectionIndex (0),
  248. atomIndex (0),
  249. wordWrapWidth (wrapWidth),
  250. passwordCharacter (passwordChar)
  251. {
  252. jassert (wordWrapWidth > 0);
  253. if (sections.size() > 0)
  254. {
  255. currentSection = sections.getUnchecked (sectionIndex);
  256. if (currentSection != nullptr)
  257. beginNewLine();
  258. }
  259. }
  260. Iterator (const Iterator& other)
  261. : indexInText (other.indexInText),
  262. lineY (other.lineY),
  263. lineHeight (other.lineHeight),
  264. maxDescent (other.maxDescent),
  265. atomX (other.atomX),
  266. atomRight (other.atomRight),
  267. atom (other.atom),
  268. currentSection (other.currentSection),
  269. sections (other.sections),
  270. sectionIndex (other.sectionIndex),
  271. atomIndex (other.atomIndex),
  272. wordWrapWidth (other.wordWrapWidth),
  273. passwordCharacter (other.passwordCharacter),
  274. tempAtom (other.tempAtom)
  275. {
  276. }
  277. //==============================================================================
  278. bool next()
  279. {
  280. if (atom == &tempAtom)
  281. {
  282. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  283. if (numRemaining > 0)
  284. {
  285. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  286. atomX = 0;
  287. if (tempAtom.numChars > 0)
  288. lineY += lineHeight;
  289. indexInText += tempAtom.numChars;
  290. GlyphArrangement g;
  291. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  292. int split;
  293. for (split = 0; split < g.getNumGlyphs(); ++split)
  294. if (shouldWrap (g.getGlyph (split).getRight()))
  295. break;
  296. if (split > 0 && split <= numRemaining)
  297. {
  298. tempAtom.numChars = (uint16) split;
  299. tempAtom.width = g.getGlyph (split - 1).getRight();
  300. atomRight = atomX + tempAtom.width;
  301. return true;
  302. }
  303. }
  304. }
  305. bool forceNewLine = false;
  306. if (sectionIndex >= sections.size())
  307. {
  308. moveToEndOfLastAtom();
  309. return false;
  310. }
  311. else if (atomIndex >= currentSection->atoms.size() - 1)
  312. {
  313. if (atomIndex >= currentSection->atoms.size())
  314. {
  315. if (++sectionIndex >= sections.size())
  316. {
  317. moveToEndOfLastAtom();
  318. return false;
  319. }
  320. atomIndex = 0;
  321. currentSection = sections.getUnchecked (sectionIndex);
  322. }
  323. else
  324. {
  325. const TextAtom* const lastAtom = currentSection->atoms.getUnchecked (atomIndex);
  326. if (! lastAtom->isWhitespace())
  327. {
  328. // handle the case where the last atom in a section is actually part of the same
  329. // word as the first atom of the next section...
  330. float right = atomRight + lastAtom->width;
  331. float lineHeight2 = lineHeight;
  332. float maxDescent2 = maxDescent;
  333. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  334. {
  335. const UniformTextSection* const s = sections.getUnchecked (section);
  336. if (s->atoms.size() == 0)
  337. break;
  338. const TextAtom* const nextAtom = s->atoms.getUnchecked (0);
  339. if (nextAtom->isWhitespace())
  340. break;
  341. right += nextAtom->width;
  342. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  343. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  344. if (shouldWrap (right))
  345. {
  346. lineHeight = lineHeight2;
  347. maxDescent = maxDescent2;
  348. forceNewLine = true;
  349. break;
  350. }
  351. if (s->atoms.size() > 1)
  352. break;
  353. }
  354. }
  355. }
  356. }
  357. if (atom != nullptr)
  358. {
  359. atomX = atomRight;
  360. indexInText += atom->numChars;
  361. if (atom->isNewLine())
  362. beginNewLine();
  363. }
  364. atom = currentSection->atoms.getUnchecked (atomIndex);
  365. atomRight = atomX + atom->width;
  366. ++atomIndex;
  367. if (shouldWrap (atomRight) || forceNewLine)
  368. {
  369. if (atom->isWhitespace())
  370. {
  371. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  372. atomRight = jmin (atomRight, wordWrapWidth);
  373. }
  374. else
  375. {
  376. atomRight = atom->width;
  377. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  378. {
  379. tempAtom = *atom;
  380. tempAtom.width = 0;
  381. tempAtom.numChars = 0;
  382. atom = &tempAtom;
  383. if (atomX > 0)
  384. beginNewLine();
  385. return next();
  386. }
  387. beginNewLine();
  388. return true;
  389. }
  390. }
  391. return true;
  392. }
  393. void beginNewLine()
  394. {
  395. atomX = 0;
  396. lineY += lineHeight;
  397. int tempSectionIndex = sectionIndex;
  398. int tempAtomIndex = atomIndex;
  399. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  400. lineHeight = section->font.getHeight();
  401. maxDescent = section->font.getDescent();
  402. float x = (atom != nullptr) ? atom->width : 0;
  403. while (! shouldWrap (x))
  404. {
  405. if (tempSectionIndex >= sections.size())
  406. break;
  407. bool checkSize = false;
  408. if (tempAtomIndex >= section->atoms.size())
  409. {
  410. if (++tempSectionIndex >= sections.size())
  411. break;
  412. tempAtomIndex = 0;
  413. section = sections.getUnchecked (tempSectionIndex);
  414. checkSize = true;
  415. }
  416. const TextAtom* const nextAtom = section->atoms.getUnchecked (tempAtomIndex);
  417. if (nextAtom == nullptr)
  418. break;
  419. x += nextAtom->width;
  420. if (shouldWrap (x) || nextAtom->isNewLine())
  421. break;
  422. if (checkSize)
  423. {
  424. lineHeight = jmax (lineHeight, section->font.getHeight());
  425. maxDescent = jmax (maxDescent, section->font.getDescent());
  426. }
  427. ++tempAtomIndex;
  428. }
  429. }
  430. //==============================================================================
  431. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  432. {
  433. if (passwordCharacter != 0 || ! atom->isWhitespace())
  434. {
  435. if (lastSection != currentSection)
  436. {
  437. lastSection = currentSection;
  438. g.setColour (currentSection->colour);
  439. g.setFont (currentSection->font);
  440. }
  441. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  442. GlyphArrangement ga;
  443. ga.addLineOfText (currentSection->font,
  444. atom->getTrimmedText (passwordCharacter),
  445. atomX, (float) roundToInt (lineY + lineHeight - maxDescent));
  446. ga.draw (g);
  447. }
  448. }
  449. void drawSelection (Graphics& g, const Range<int> selected) const
  450. {
  451. const int startX = roundToInt (indexToX (selected.getStart()));
  452. const int endX = roundToInt (indexToX (selected.getEnd()));
  453. const int y = roundToInt (lineY);
  454. const int nextY = roundToInt (lineY + lineHeight);
  455. g.fillRect (startX, y, endX - startX, nextY - y);
  456. }
  457. void drawUnderline (Graphics& g, const Range<int> underline, const Colour colour) const
  458. {
  459. const int startX = roundToInt (indexToX (underline.getStart()));
  460. const int endX = roundToInt (indexToX (underline.getEnd()));
  461. const int baselineY = roundToInt (lineY + currentSection->font.getAscent() + 0.5f);
  462. Graphics::ScopedSaveState state (g);
  463. g.reduceClipRegion (Rectangle<int> (startX, baselineY, endX - startX, 1));
  464. g.fillCheckerBoard (Rectangle<int> (endX, baselineY + 1), 3, 1, colour, Colours::transparentBlack);
  465. }
  466. void drawSelectedText (Graphics& g,
  467. const Range<int> selected,
  468. const Colour selectedTextColour) const
  469. {
  470. if (passwordCharacter != 0 || ! atom->isWhitespace())
  471. {
  472. GlyphArrangement ga;
  473. ga.addLineOfText (currentSection->font,
  474. atom->getTrimmedText (passwordCharacter),
  475. atomX, (float) roundToInt (lineY + lineHeight - maxDescent));
  476. if (selected.getEnd() < indexInText + atom->numChars)
  477. {
  478. GlyphArrangement ga2 (ga);
  479. ga2.removeRangeOfGlyphs (0, selected.getEnd() - indexInText);
  480. ga.removeRangeOfGlyphs (selected.getEnd() - indexInText, -1);
  481. g.setColour (currentSection->colour);
  482. ga2.draw (g);
  483. }
  484. if (selected.getStart() > indexInText)
  485. {
  486. GlyphArrangement ga2 (ga);
  487. ga2.removeRangeOfGlyphs (selected.getStart() - indexInText, -1);
  488. ga.removeRangeOfGlyphs (0, selected.getStart() - indexInText);
  489. g.setColour (currentSection->colour);
  490. ga2.draw (g);
  491. }
  492. g.setColour (selectedTextColour);
  493. ga.draw (g);
  494. }
  495. }
  496. //==============================================================================
  497. float indexToX (const int indexToFind) const
  498. {
  499. if (indexToFind <= indexInText)
  500. return atomX;
  501. if (indexToFind >= indexInText + atom->numChars)
  502. return atomRight;
  503. GlyphArrangement g;
  504. g.addLineOfText (currentSection->font,
  505. atom->getText (passwordCharacter),
  506. atomX, 0.0f);
  507. if (indexToFind - indexInText >= g.getNumGlyphs())
  508. return atomRight;
  509. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  510. }
  511. int xToIndex (const float xToFind) const
  512. {
  513. if (xToFind <= atomX || atom->isNewLine())
  514. return indexInText;
  515. if (xToFind >= atomRight)
  516. return indexInText + atom->numChars;
  517. GlyphArrangement g;
  518. g.addLineOfText (currentSection->font,
  519. atom->getText (passwordCharacter),
  520. atomX, 0.0f);
  521. const int numGlyphs = g.getNumGlyphs();
  522. int j;
  523. for (j = 0; j < numGlyphs; ++j)
  524. {
  525. const PositionedGlyph& pg = g.getGlyph(j);
  526. if ((pg.getLeft() + pg.getRight()) / 2 > xToFind)
  527. break;
  528. }
  529. return indexInText + j;
  530. }
  531. //==============================================================================
  532. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeightFound)
  533. {
  534. while (next())
  535. {
  536. if (indexInText + atom->numChars > index)
  537. {
  538. cx = indexToX (index);
  539. cy = lineY;
  540. lineHeightFound = lineHeight;
  541. return true;
  542. }
  543. }
  544. cx = atomX;
  545. cy = lineY;
  546. lineHeightFound = lineHeight;
  547. return false;
  548. }
  549. //==============================================================================
  550. int indexInText;
  551. float lineY, lineHeight, maxDescent;
  552. float atomX, atomRight;
  553. const TextAtom* atom;
  554. const UniformTextSection* currentSection;
  555. private:
  556. const Array <UniformTextSection*>& sections;
  557. int sectionIndex, atomIndex;
  558. const float wordWrapWidth;
  559. const juce_wchar passwordCharacter;
  560. TextAtom tempAtom;
  561. Iterator& operator= (const Iterator&);
  562. void moveToEndOfLastAtom()
  563. {
  564. if (atom != nullptr)
  565. {
  566. atomX = atomRight;
  567. if (atom->isNewLine())
  568. {
  569. atomX = 0.0f;
  570. lineY += lineHeight;
  571. }
  572. }
  573. }
  574. bool shouldWrap (const float x) const noexcept
  575. {
  576. return (x - 0.0001f) >= wordWrapWidth;
  577. }
  578. JUCE_LEAK_DETECTOR (Iterator)
  579. };
  580. //==============================================================================
  581. class TextEditor::InsertAction : public UndoableAction
  582. {
  583. public:
  584. InsertAction (TextEditor& ed,
  585. const String& newText,
  586. const int insertPos,
  587. const Font& newFont,
  588. const Colour newColour,
  589. const int oldCaret,
  590. const int newCaret)
  591. : owner (ed),
  592. text (newText),
  593. insertIndex (insertPos),
  594. oldCaretPos (oldCaret),
  595. newCaretPos (newCaret),
  596. font (newFont),
  597. colour (newColour)
  598. {
  599. }
  600. bool perform()
  601. {
  602. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  603. return true;
  604. }
  605. bool undo()
  606. {
  607. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  608. return true;
  609. }
  610. int getSizeInUnits()
  611. {
  612. return text.length() + 16;
  613. }
  614. private:
  615. TextEditor& owner;
  616. const String text;
  617. const int insertIndex, oldCaretPos, newCaretPos;
  618. const Font font;
  619. const Colour colour;
  620. JUCE_DECLARE_NON_COPYABLE (InsertAction)
  621. };
  622. //==============================================================================
  623. class TextEditor::RemoveAction : public UndoableAction
  624. {
  625. public:
  626. RemoveAction (TextEditor& ed,
  627. const Range<int> rangeToRemove,
  628. const int oldCaret,
  629. const int newCaret,
  630. const Array <UniformTextSection*>& oldSections)
  631. : owner (ed),
  632. range (rangeToRemove),
  633. oldCaretPos (oldCaret),
  634. newCaretPos (newCaret),
  635. removedSections (oldSections)
  636. {
  637. }
  638. ~RemoveAction()
  639. {
  640. for (int i = removedSections.size(); --i >= 0;)
  641. {
  642. ScopedPointer<UniformTextSection> section (removedSections.getUnchecked (i));
  643. section->clear();
  644. }
  645. }
  646. bool perform()
  647. {
  648. owner.remove (range, 0, newCaretPos);
  649. return true;
  650. }
  651. bool undo()
  652. {
  653. owner.reinsert (range.getStart(), removedSections);
  654. owner.moveCaretTo (oldCaretPos, false);
  655. return true;
  656. }
  657. int getSizeInUnits()
  658. {
  659. int n = 16;
  660. for (int i = removedSections.size(); --i >= 0;)
  661. n += removedSections.getUnchecked (i)->getTotalLength();
  662. return n;
  663. }
  664. private:
  665. TextEditor& owner;
  666. const Range<int> range;
  667. const int oldCaretPos, newCaretPos;
  668. Array <UniformTextSection*> removedSections;
  669. JUCE_DECLARE_NON_COPYABLE (RemoveAction)
  670. };
  671. //==============================================================================
  672. class TextEditor::TextHolderComponent : public Component,
  673. public Timer,
  674. public ValueListener
  675. {
  676. public:
  677. TextHolderComponent (TextEditor& ed) : owner (ed)
  678. {
  679. setWantsKeyboardFocus (false);
  680. setInterceptsMouseClicks (false, true);
  681. setMouseCursor (MouseCursor::ParentCursor);
  682. owner.getTextValue().addListener (this);
  683. }
  684. ~TextHolderComponent()
  685. {
  686. owner.getTextValue().removeListener (this);
  687. }
  688. void paint (Graphics& g) override
  689. {
  690. owner.drawContent (g);
  691. }
  692. void restartTimer()
  693. {
  694. startTimer (350);
  695. }
  696. void timerCallback() override
  697. {
  698. owner.timerCallbackInt();
  699. }
  700. void valueChanged (Value&) override
  701. {
  702. owner.textWasChangedByValue();
  703. }
  704. private:
  705. TextEditor& owner;
  706. JUCE_DECLARE_NON_COPYABLE (TextHolderComponent)
  707. };
  708. //==============================================================================
  709. class TextEditorViewport : public Viewport
  710. {
  711. public:
  712. TextEditorViewport (TextEditor& ed)
  713. : owner (ed), lastWordWrapWidth (0), rentrant (false)
  714. {
  715. }
  716. void visibleAreaChanged (const Rectangle<int>&) override
  717. {
  718. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  719. // appear and disappear, causing the wrap width to change.
  720. {
  721. const float wordWrapWidth = owner.getWordWrapWidth();
  722. if (wordWrapWidth != lastWordWrapWidth)
  723. {
  724. lastWordWrapWidth = wordWrapWidth;
  725. rentrant = true;
  726. owner.updateTextHolderSize();
  727. rentrant = false;
  728. }
  729. }
  730. }
  731. private:
  732. TextEditor& owner;
  733. float lastWordWrapWidth;
  734. bool rentrant;
  735. JUCE_DECLARE_NON_COPYABLE (TextEditorViewport)
  736. };
  737. //==============================================================================
  738. namespace TextEditorDefs
  739. {
  740. const int textChangeMessageId = 0x10003001;
  741. const int returnKeyMessageId = 0x10003002;
  742. const int escapeKeyMessageId = 0x10003003;
  743. const int focusLossMessageId = 0x10003004;
  744. const int maxActionsPerTransaction = 100;
  745. static int getCharacterCategory (const juce_wchar character)
  746. {
  747. return CharacterFunctions::isLetterOrDigit (character)
  748. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  749. }
  750. }
  751. //==============================================================================
  752. TextEditor::TextEditor (const String& name,
  753. const juce_wchar passwordChar)
  754. : Component (name),
  755. borderSize (1, 1, 1, 3),
  756. readOnly (false),
  757. multiline (false),
  758. wordWrap (false),
  759. returnKeyStartsNewLine (false),
  760. popupMenuEnabled (true),
  761. selectAllTextWhenFocused (false),
  762. scrollbarVisible (true),
  763. wasFocused (false),
  764. keepCaretOnScreen (true),
  765. tabKeyUsed (false),
  766. menuActive (false),
  767. valueTextNeedsUpdating (false),
  768. consumeEscAndReturnKeys (true),
  769. leftIndent (4),
  770. topIndent (4),
  771. lastTransactionTime (0),
  772. currentFont (14.0f),
  773. totalNumChars (0),
  774. caretPosition (0),
  775. passwordCharacter (passwordChar),
  776. dragType (notDragging)
  777. {
  778. setOpaque (true);
  779. setMouseCursor (MouseCursor::IBeamCursor);
  780. addAndMakeVisible (viewport = new TextEditorViewport (*this));
  781. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  782. viewport->setWantsKeyboardFocus (false);
  783. viewport->setScrollBarsShown (false, false);
  784. setWantsKeyboardFocus (true);
  785. setCaretVisible (true);
  786. }
  787. TextEditor::~TextEditor()
  788. {
  789. if (wasFocused)
  790. if (ComponentPeer* const peer = getPeer())
  791. peer->dismissPendingTextInput();
  792. textValue.removeListener (textHolder);
  793. textValue.referTo (Value());
  794. clearInternal (0);
  795. viewport = nullptr;
  796. textHolder = nullptr;
  797. }
  798. //==============================================================================
  799. void TextEditor::newTransaction()
  800. {
  801. lastTransactionTime = Time::getApproximateMillisecondCounter();
  802. undoManager.beginNewTransaction();
  803. }
  804. bool TextEditor::undoOrRedo (const bool shouldUndo)
  805. {
  806. if (! isReadOnly())
  807. {
  808. newTransaction();
  809. if (shouldUndo ? undoManager.undo()
  810. : undoManager.redo())
  811. {
  812. scrollToMakeSureCursorIsVisible();
  813. repaint();
  814. textChanged();
  815. return true;
  816. }
  817. }
  818. return false;
  819. }
  820. bool TextEditor::undo() { return undoOrRedo (true); }
  821. bool TextEditor::redo() { return undoOrRedo (false); }
  822. //==============================================================================
  823. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  824. const bool shouldWordWrap)
  825. {
  826. if (multiline != shouldBeMultiLine
  827. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  828. {
  829. multiline = shouldBeMultiLine;
  830. wordWrap = shouldWordWrap && shouldBeMultiLine;
  831. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  832. scrollbarVisible && multiline);
  833. viewport->setViewPosition (0, 0);
  834. resized();
  835. scrollToMakeSureCursorIsVisible();
  836. }
  837. }
  838. bool TextEditor::isMultiLine() const
  839. {
  840. return multiline;
  841. }
  842. void TextEditor::setScrollbarsShown (bool shown)
  843. {
  844. if (scrollbarVisible != shown)
  845. {
  846. scrollbarVisible = shown;
  847. shown = shown && isMultiLine();
  848. viewport->setScrollBarsShown (shown, shown);
  849. }
  850. }
  851. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  852. {
  853. if (readOnly != shouldBeReadOnly)
  854. {
  855. readOnly = shouldBeReadOnly;
  856. enablementChanged();
  857. }
  858. }
  859. bool TextEditor::isReadOnly() const
  860. {
  861. return readOnly || ! isEnabled();
  862. }
  863. bool TextEditor::isTextInputActive() const
  864. {
  865. return ! isReadOnly();
  866. }
  867. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  868. {
  869. returnKeyStartsNewLine = shouldStartNewLine;
  870. }
  871. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  872. {
  873. tabKeyUsed = shouldTabKeyBeUsed;
  874. }
  875. void TextEditor::setPopupMenuEnabled (const bool b)
  876. {
  877. popupMenuEnabled = b;
  878. }
  879. void TextEditor::setSelectAllWhenFocused (const bool b)
  880. {
  881. selectAllTextWhenFocused = b;
  882. }
  883. //==============================================================================
  884. void TextEditor::setFont (const Font& newFont)
  885. {
  886. currentFont = newFont;
  887. scrollToMakeSureCursorIsVisible();
  888. }
  889. void TextEditor::applyFontToAllText (const Font& newFont)
  890. {
  891. currentFont = newFont;
  892. const Colour overallColour (findColour (textColourId));
  893. for (int i = sections.size(); --i >= 0;)
  894. {
  895. UniformTextSection* const uts = sections.getUnchecked (i);
  896. uts->setFont (newFont, passwordCharacter);
  897. uts->colour = overallColour;
  898. }
  899. coalesceSimilarSections();
  900. updateTextHolderSize();
  901. scrollToMakeSureCursorIsVisible();
  902. repaint();
  903. }
  904. void TextEditor::colourChanged()
  905. {
  906. setOpaque (findColour (backgroundColourId).isOpaque());
  907. repaint();
  908. }
  909. void TextEditor::lookAndFeelChanged()
  910. {
  911. if (isCaretVisible())
  912. {
  913. setCaretVisible (false);
  914. setCaretVisible (true);
  915. updateCaretPosition();
  916. }
  917. }
  918. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  919. {
  920. if (shouldCaretBeVisible && ! isReadOnly())
  921. {
  922. if (caret == nullptr)
  923. textHolder->addChildComponent (caret = getLookAndFeel().createCaretComponent (this));
  924. }
  925. else
  926. {
  927. caret = nullptr;
  928. }
  929. }
  930. void TextEditor::updateCaretPosition()
  931. {
  932. if (caret != nullptr)
  933. caret->setCaretPosition (getCaretRectangle().translated (leftIndent, topIndent));
  934. }
  935. TextEditor::LengthAndCharacterRestriction::LengthAndCharacterRestriction (int maxLen, const String& chars)
  936. : allowedCharacters (chars), maxLength (maxLen)
  937. {}
  938. String TextEditor::LengthAndCharacterRestriction::filterNewText (TextEditor& ed, const String& newInput)
  939. {
  940. String t (newInput);
  941. if (allowedCharacters.isNotEmpty())
  942. t = t.retainCharacters (allowedCharacters);
  943. if (maxLength > 0)
  944. t = t.substring (0, maxLength - (ed.getTotalNumChars() - ed.getHighlightedRegion().getLength()));
  945. return t;
  946. }
  947. void TextEditor::setInputFilter (InputFilter* newFilter, bool takeOwnership)
  948. {
  949. inputFilter.set (newFilter, takeOwnership);
  950. }
  951. void TextEditor::setInputRestrictions (const int maxLen,
  952. const String& chars)
  953. {
  954. setInputFilter (new LengthAndCharacterRestriction (maxLen, chars), true);
  955. }
  956. void TextEditor::setTextToShowWhenEmpty (const String& text, Colour colourToUse)
  957. {
  958. textToShowWhenEmpty = text;
  959. colourForTextWhenEmpty = colourToUse;
  960. }
  961. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  962. {
  963. if (passwordCharacter != newPasswordCharacter)
  964. {
  965. passwordCharacter = newPasswordCharacter;
  966. applyFontToAllText (currentFont);
  967. }
  968. }
  969. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  970. {
  971. viewport->setScrollBarThickness (newThicknessPixels);
  972. }
  973. //==============================================================================
  974. void TextEditor::clear()
  975. {
  976. clearInternal (0);
  977. updateTextHolderSize();
  978. undoManager.clearUndoHistory();
  979. }
  980. void TextEditor::setText (const String& newText,
  981. const bool sendTextChangeMessage)
  982. {
  983. const int newLength = newText.length();
  984. if (newLength != getTotalNumChars() || getText() != newText)
  985. {
  986. textValue = newText;
  987. int oldCursorPos = caretPosition;
  988. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  989. clearInternal (0);
  990. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  991. // if you're adding text with line-feeds to a single-line text editor, it
  992. // ain't gonna look right!
  993. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  994. if (cursorWasAtEnd && ! isMultiLine())
  995. oldCursorPos = getTotalNumChars();
  996. moveCaretTo (oldCursorPos, false);
  997. if (sendTextChangeMessage)
  998. textChanged();
  999. updateTextHolderSize();
  1000. scrollToMakeSureCursorIsVisible();
  1001. undoManager.clearUndoHistory();
  1002. repaint();
  1003. }
  1004. }
  1005. //==============================================================================
  1006. void TextEditor::updateValueFromText()
  1007. {
  1008. if (valueTextNeedsUpdating)
  1009. {
  1010. valueTextNeedsUpdating = false;
  1011. textValue = getText();
  1012. }
  1013. }
  1014. Value& TextEditor::getTextValue()
  1015. {
  1016. updateValueFromText();
  1017. return textValue;
  1018. }
  1019. void TextEditor::textWasChangedByValue()
  1020. {
  1021. if (textValue.getValueSource().getReferenceCount() > 1)
  1022. setText (textValue.getValue());
  1023. }
  1024. //==============================================================================
  1025. void TextEditor::textChanged()
  1026. {
  1027. updateTextHolderSize();
  1028. if (listeners.size() > 0)
  1029. postCommandMessage (TextEditorDefs::textChangeMessageId);
  1030. if (textValue.getValueSource().getReferenceCount() > 1)
  1031. {
  1032. valueTextNeedsUpdating = false;
  1033. textValue = getText();
  1034. }
  1035. }
  1036. void TextEditor::returnPressed() { postCommandMessage (TextEditorDefs::returnKeyMessageId); }
  1037. void TextEditor::escapePressed() { postCommandMessage (TextEditorDefs::escapeKeyMessageId); }
  1038. void TextEditor::addListener (TextEditorListener* const l) { listeners.add (l); }
  1039. void TextEditor::removeListener (TextEditorListener* const l) { listeners.remove (l); }
  1040. //==============================================================================
  1041. void TextEditor::timerCallbackInt()
  1042. {
  1043. if (hasKeyboardFocus (false) && ! isCurrentlyBlockedByAnotherModalComponent())
  1044. wasFocused = true;
  1045. const unsigned int now = Time::getApproximateMillisecondCounter();
  1046. if (now > lastTransactionTime + 200)
  1047. newTransaction();
  1048. }
  1049. void TextEditor::repaintText (const Range<int> range)
  1050. {
  1051. if (! range.isEmpty())
  1052. {
  1053. float x = 0, y = 0, lh = currentFont.getHeight();
  1054. const float wordWrapWidth = getWordWrapWidth();
  1055. if (wordWrapWidth > 0)
  1056. {
  1057. Iterator i (sections, wordWrapWidth, passwordCharacter);
  1058. i.getCharPosition (range.getStart(), x, y, lh);
  1059. const int y1 = (int) y;
  1060. int y2;
  1061. if (range.getEnd() >= getTotalNumChars())
  1062. {
  1063. y2 = textHolder->getHeight();
  1064. }
  1065. else
  1066. {
  1067. i.getCharPosition (range.getEnd(), x, y, lh);
  1068. y2 = (int) (y + lh * 2.0f);
  1069. }
  1070. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  1071. }
  1072. }
  1073. }
  1074. //==============================================================================
  1075. void TextEditor::moveCaret (int newCaretPos)
  1076. {
  1077. if (newCaretPos < 0)
  1078. newCaretPos = 0;
  1079. else if (newCaretPos > getTotalNumChars())
  1080. newCaretPos = getTotalNumChars();
  1081. if (newCaretPos != getCaretPosition())
  1082. {
  1083. caretPosition = newCaretPos;
  1084. textHolder->restartTimer();
  1085. scrollToMakeSureCursorIsVisible();
  1086. updateCaretPosition();
  1087. }
  1088. }
  1089. int TextEditor::getCaretPosition() const
  1090. {
  1091. return caretPosition;
  1092. }
  1093. void TextEditor::setCaretPosition (const int newIndex)
  1094. {
  1095. moveCaretTo (newIndex, false);
  1096. }
  1097. void TextEditor::moveCaretToEnd()
  1098. {
  1099. moveCaretTo (std::numeric_limits<int>::max(), false);
  1100. }
  1101. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  1102. const int desiredCaretY)
  1103. {
  1104. updateCaretPosition();
  1105. const Rectangle<int> caretPos (getCaretRectangle());
  1106. int vx = caretPos.getX() - desiredCaretX;
  1107. int vy = caretPos.getY() - desiredCaretY;
  1108. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  1109. vx += desiredCaretX - proportionOfWidth (0.2f);
  1110. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  1111. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  1112. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  1113. if (! isMultiLine())
  1114. {
  1115. vy = viewport->getViewPositionY();
  1116. }
  1117. else
  1118. {
  1119. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  1120. if (desiredCaretY < 0)
  1121. vy = jmax (0, desiredCaretY + vy);
  1122. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - caretPos.getHeight()))
  1123. vy += desiredCaretY + 2 + caretPos.getHeight() + topIndent - viewport->getMaximumVisibleHeight();
  1124. }
  1125. viewport->setViewPosition (vx, vy);
  1126. }
  1127. Rectangle<int> TextEditor::getCaretRectangle()
  1128. {
  1129. float cursorX, cursorY;
  1130. float cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  1131. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  1132. return Rectangle<int> (roundToInt (cursorX), roundToInt (cursorY), 2, roundToInt (cursorHeight));
  1133. }
  1134. //==============================================================================
  1135. enum { rightEdgeSpace = 2 };
  1136. float TextEditor::getWordWrapWidth() const
  1137. {
  1138. return wordWrap ? (float) (viewport->getMaximumVisibleWidth() - (leftIndent + rightEdgeSpace + 1))
  1139. : std::numeric_limits<float>::max();
  1140. }
  1141. void TextEditor::updateTextHolderSize()
  1142. {
  1143. const float wordWrapWidth = getWordWrapWidth();
  1144. if (wordWrapWidth > 0)
  1145. {
  1146. float maxWidth = 0.0f;
  1147. Iterator i (sections, wordWrapWidth, passwordCharacter);
  1148. while (i.next())
  1149. maxWidth = jmax (maxWidth, i.atomRight);
  1150. const int w = leftIndent + roundToInt (maxWidth);
  1151. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  1152. currentFont.getHeight()));
  1153. textHolder->setSize (w + rightEdgeSpace, h + 1); // (allows a bit of space for the cursor to be at the right-hand-edge)
  1154. }
  1155. }
  1156. int TextEditor::getTextWidth() const { return textHolder->getWidth(); }
  1157. int TextEditor::getTextHeight() const { return textHolder->getHeight(); }
  1158. void TextEditor::setIndents (const int newLeftIndent, const int newTopIndent)
  1159. {
  1160. leftIndent = newLeftIndent;
  1161. topIndent = newTopIndent;
  1162. }
  1163. void TextEditor::setBorder (const BorderSize<int>& border)
  1164. {
  1165. borderSize = border;
  1166. resized();
  1167. }
  1168. BorderSize<int> TextEditor::getBorder() const
  1169. {
  1170. return borderSize;
  1171. }
  1172. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  1173. {
  1174. keepCaretOnScreen = shouldScrollToShowCursor;
  1175. }
  1176. void TextEditor::scrollToMakeSureCursorIsVisible()
  1177. {
  1178. updateCaretPosition();
  1179. if (keepCaretOnScreen)
  1180. {
  1181. int x = viewport->getViewPositionX();
  1182. int y = viewport->getViewPositionY();
  1183. const Rectangle<int> caretPos (getCaretRectangle());
  1184. const int relativeCursorX = caretPos.getX() - x;
  1185. const int relativeCursorY = caretPos.getY() - y;
  1186. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  1187. {
  1188. x += relativeCursorX - proportionOfWidth (0.2f);
  1189. }
  1190. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  1191. {
  1192. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  1193. }
  1194. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  1195. if (! isMultiLine())
  1196. {
  1197. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  1198. }
  1199. else
  1200. {
  1201. if (relativeCursorY < 0)
  1202. {
  1203. y = jmax (0, relativeCursorY + y);
  1204. }
  1205. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - caretPos.getHeight()))
  1206. {
  1207. y += relativeCursorY + 2 + caretPos.getHeight() + topIndent - viewport->getMaximumVisibleHeight();
  1208. }
  1209. }
  1210. viewport->setViewPosition (x, y);
  1211. }
  1212. }
  1213. void TextEditor::moveCaretTo (const int newPosition,
  1214. const bool isSelecting)
  1215. {
  1216. if (isSelecting)
  1217. {
  1218. moveCaret (newPosition);
  1219. const Range<int> oldSelection (selection);
  1220. if (dragType == notDragging)
  1221. {
  1222. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  1223. dragType = draggingSelectionStart;
  1224. else
  1225. dragType = draggingSelectionEnd;
  1226. }
  1227. if (dragType == draggingSelectionStart)
  1228. {
  1229. if (getCaretPosition() >= selection.getEnd())
  1230. dragType = draggingSelectionEnd;
  1231. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  1232. }
  1233. else
  1234. {
  1235. if (getCaretPosition() < selection.getStart())
  1236. dragType = draggingSelectionStart;
  1237. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  1238. }
  1239. repaintText (selection.getUnionWith (oldSelection));
  1240. }
  1241. else
  1242. {
  1243. dragType = notDragging;
  1244. repaintText (selection);
  1245. moveCaret (newPosition);
  1246. selection = Range<int>::emptyRange (getCaretPosition());
  1247. }
  1248. }
  1249. int TextEditor::getTextIndexAt (const int x, const int y)
  1250. {
  1251. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  1252. (float) (y + viewport->getViewPositionY() - topIndent));
  1253. }
  1254. void TextEditor::insertTextAtCaret (const String& t)
  1255. {
  1256. String newText (inputFilter != nullptr ? inputFilter->filterNewText (*this, t) : t);
  1257. if (isMultiLine())
  1258. newText = newText.replace ("\r\n", "\n");
  1259. else
  1260. newText = newText.replaceCharacters ("\r\n", " ");
  1261. const int insertIndex = selection.getStart();
  1262. const int newCaretPos = insertIndex + newText.length();
  1263. remove (selection, getUndoManager(),
  1264. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  1265. insert (newText, insertIndex, currentFont, findColour (textColourId),
  1266. getUndoManager(), newCaretPos);
  1267. textChanged();
  1268. }
  1269. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  1270. {
  1271. moveCaretTo (newSelection.getStart(), false);
  1272. moveCaretTo (newSelection.getEnd(), true);
  1273. }
  1274. //==============================================================================
  1275. void TextEditor::copy()
  1276. {
  1277. if (passwordCharacter == 0)
  1278. {
  1279. const String selectedText (getHighlightedText());
  1280. if (selectedText.isNotEmpty())
  1281. SystemClipboard::copyTextToClipboard (selectedText);
  1282. }
  1283. }
  1284. void TextEditor::paste()
  1285. {
  1286. if (! isReadOnly())
  1287. {
  1288. const String clip (SystemClipboard::getTextFromClipboard());
  1289. if (clip.isNotEmpty())
  1290. insertTextAtCaret (clip);
  1291. }
  1292. }
  1293. void TextEditor::cut()
  1294. {
  1295. if (! isReadOnly())
  1296. {
  1297. moveCaret (selection.getEnd());
  1298. insertTextAtCaret (String::empty);
  1299. }
  1300. }
  1301. //==============================================================================
  1302. void TextEditor::drawContent (Graphics& g)
  1303. {
  1304. const float wordWrapWidth = getWordWrapWidth();
  1305. if (wordWrapWidth > 0)
  1306. {
  1307. g.setOrigin (leftIndent, topIndent);
  1308. const Rectangle<int> clip (g.getClipBounds());
  1309. Colour selectedTextColour;
  1310. Iterator i (sections, wordWrapWidth, passwordCharacter);
  1311. while (i.lineY + 200.0 < clip.getY() && i.next())
  1312. {}
  1313. if (! selection.isEmpty())
  1314. {
  1315. g.setColour (findColour (highlightColourId).withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  1316. selectedTextColour = findColour (highlightedTextColourId);
  1317. Iterator i2 (i);
  1318. while (i2.next() && i2.lineY < clip.getBottom())
  1319. {
  1320. if (i2.lineY + i2.lineHeight >= clip.getY()
  1321. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  1322. {
  1323. i2.drawSelection (g, selection);
  1324. }
  1325. }
  1326. }
  1327. const UniformTextSection* lastSection = nullptr;
  1328. while (i.next() && i.lineY < clip.getBottom())
  1329. {
  1330. if (i.lineY + i.lineHeight >= clip.getY())
  1331. {
  1332. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  1333. {
  1334. i.drawSelectedText (g, selection, selectedTextColour);
  1335. lastSection = nullptr;
  1336. }
  1337. else
  1338. {
  1339. i.draw (g, lastSection);
  1340. }
  1341. }
  1342. }
  1343. for (int j = underlinedSections.size(); --j >= 0;)
  1344. {
  1345. const Range<int> underlinedSection = underlinedSections.getReference (j);
  1346. Iterator i2 (sections, wordWrapWidth, passwordCharacter);
  1347. while (i2.next() && i2.lineY < clip.getBottom())
  1348. {
  1349. if (i2.lineY + i2.lineHeight >= clip.getY()
  1350. && underlinedSection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  1351. {
  1352. i2.drawUnderline (g, underlinedSection, findColour (textColourId));
  1353. }
  1354. }
  1355. }
  1356. }
  1357. }
  1358. void TextEditor::paint (Graphics& g)
  1359. {
  1360. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  1361. }
  1362. void TextEditor::paintOverChildren (Graphics& g)
  1363. {
  1364. if (textToShowWhenEmpty.isNotEmpty()
  1365. && (! hasKeyboardFocus (false))
  1366. && getTotalNumChars() == 0)
  1367. {
  1368. g.setColour (colourForTextWhenEmpty);
  1369. g.setFont (getFont());
  1370. if (isMultiLine())
  1371. g.drawText (textToShowWhenEmpty, getLocalBounds(),
  1372. Justification::centred, true);
  1373. else
  1374. g.drawText (textToShowWhenEmpty,
  1375. leftIndent, 0, viewport->getWidth() - leftIndent, getHeight(),
  1376. Justification::centredLeft, true);
  1377. }
  1378. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  1379. }
  1380. //==============================================================================
  1381. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  1382. {
  1383. const bool writable = ! isReadOnly();
  1384. if (passwordCharacter == 0)
  1385. {
  1386. m.addItem (StandardApplicationCommandIDs::cut, TRANS("Cut"), writable);
  1387. m.addItem (StandardApplicationCommandIDs::copy, TRANS("Copy"), ! selection.isEmpty());
  1388. m.addItem (StandardApplicationCommandIDs::paste, TRANS("Paste"), writable);
  1389. }
  1390. m.addItem (StandardApplicationCommandIDs::del, TRANS("Delete"), writable);
  1391. m.addSeparator();
  1392. m.addItem (StandardApplicationCommandIDs::selectAll, TRANS("Select All"));
  1393. m.addSeparator();
  1394. if (getUndoManager() != nullptr)
  1395. {
  1396. m.addItem (StandardApplicationCommandIDs::undo, TRANS("Undo"), undoManager.canUndo());
  1397. m.addItem (StandardApplicationCommandIDs::redo, TRANS("Redo"), undoManager.canRedo());
  1398. }
  1399. }
  1400. void TextEditor::performPopupMenuAction (const int menuItemID)
  1401. {
  1402. switch (menuItemID)
  1403. {
  1404. case StandardApplicationCommandIDs::cut: cutToClipboard(); break;
  1405. case StandardApplicationCommandIDs::copy: copyToClipboard(); break;
  1406. case StandardApplicationCommandIDs::paste: pasteFromClipboard(); break;
  1407. case StandardApplicationCommandIDs::del: cut(); break;
  1408. case StandardApplicationCommandIDs::selectAll: selectAll(); break;
  1409. case StandardApplicationCommandIDs::undo: undo(); break;
  1410. case StandardApplicationCommandIDs::redo: redo(); break;
  1411. default: break;
  1412. }
  1413. }
  1414. static void textEditorMenuCallback (int menuResult, TextEditor* editor)
  1415. {
  1416. if (editor != nullptr && menuResult != 0)
  1417. editor->performPopupMenuAction (menuResult);
  1418. }
  1419. //==============================================================================
  1420. void TextEditor::mouseDown (const MouseEvent& e)
  1421. {
  1422. beginDragAutoRepeat (100);
  1423. newTransaction();
  1424. if (wasFocused || ! selectAllTextWhenFocused)
  1425. {
  1426. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  1427. {
  1428. moveCaretTo (getTextIndexAt (e.x, e.y),
  1429. e.mods.isShiftDown());
  1430. }
  1431. else
  1432. {
  1433. PopupMenu m;
  1434. m.setLookAndFeel (&getLookAndFeel());
  1435. addPopupMenuItems (m, &e);
  1436. m.showMenuAsync (PopupMenu::Options(),
  1437. ModalCallbackFunction::forComponent (textEditorMenuCallback, this));
  1438. }
  1439. }
  1440. }
  1441. void TextEditor::mouseDrag (const MouseEvent& e)
  1442. {
  1443. if (wasFocused || ! selectAllTextWhenFocused)
  1444. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  1445. moveCaretTo (getTextIndexAt (e.x, e.y), true);
  1446. }
  1447. void TextEditor::mouseUp (const MouseEvent& e)
  1448. {
  1449. newTransaction();
  1450. textHolder->restartTimer();
  1451. if (wasFocused || ! selectAllTextWhenFocused)
  1452. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  1453. moveCaret (getTextIndexAt (e.x, e.y));
  1454. wasFocused = true;
  1455. }
  1456. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  1457. {
  1458. int tokenEnd = getTextIndexAt (e.x, e.y);
  1459. int tokenStart = 0;
  1460. if (e.getNumberOfClicks() > 3)
  1461. {
  1462. tokenEnd = getTotalNumChars();
  1463. }
  1464. else
  1465. {
  1466. const String t (getText());
  1467. const int totalLength = getTotalNumChars();
  1468. while (tokenEnd < totalLength)
  1469. {
  1470. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  1471. const juce_wchar c = t [tokenEnd];
  1472. if (CharacterFunctions::isLetterOrDigit (c) || c > 128)
  1473. ++tokenEnd;
  1474. else
  1475. break;
  1476. }
  1477. tokenStart = tokenEnd;
  1478. while (tokenStart > 0)
  1479. {
  1480. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  1481. const juce_wchar c = t [tokenStart - 1];
  1482. if (CharacterFunctions::isLetterOrDigit (c) || c > 128)
  1483. --tokenStart;
  1484. else
  1485. break;
  1486. }
  1487. if (e.getNumberOfClicks() > 2)
  1488. {
  1489. while (tokenEnd < totalLength)
  1490. {
  1491. const juce_wchar c = t [tokenEnd];
  1492. if (c != '\r' && c != '\n')
  1493. ++tokenEnd;
  1494. else
  1495. break;
  1496. }
  1497. while (tokenStart > 0)
  1498. {
  1499. const juce_wchar c = t [tokenStart - 1];
  1500. if (c != '\r' && c != '\n')
  1501. --tokenStart;
  1502. else
  1503. break;
  1504. }
  1505. }
  1506. }
  1507. moveCaretTo (tokenEnd, false);
  1508. moveCaretTo (tokenStart, true);
  1509. }
  1510. void TextEditor::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  1511. {
  1512. if (! viewport->useMouseWheelMoveIfNeeded (e, wheel))
  1513. Component::mouseWheelMove (e, wheel);
  1514. }
  1515. //==============================================================================
  1516. bool TextEditor::moveCaretWithTransaction (const int newPos, const bool selecting)
  1517. {
  1518. newTransaction();
  1519. moveCaretTo (newPos, selecting);
  1520. return true;
  1521. }
  1522. bool TextEditor::moveCaretLeft (bool moveInWholeWordSteps, bool selecting)
  1523. {
  1524. int pos = getCaretPosition();
  1525. if (moveInWholeWordSteps)
  1526. pos = findWordBreakBefore (pos);
  1527. else
  1528. --pos;
  1529. return moveCaretWithTransaction (pos, selecting);
  1530. }
  1531. bool TextEditor::moveCaretRight (bool moveInWholeWordSteps, bool selecting)
  1532. {
  1533. int pos = getCaretPosition();
  1534. if (moveInWholeWordSteps)
  1535. pos = findWordBreakAfter (pos);
  1536. else
  1537. ++pos;
  1538. return moveCaretWithTransaction (pos, selecting);
  1539. }
  1540. bool TextEditor::moveCaretUp (bool selecting)
  1541. {
  1542. if (! isMultiLine())
  1543. return moveCaretToStartOfLine (selecting);
  1544. const Rectangle<float> caretPos (getCaretRectangle().toFloat());
  1545. return moveCaretWithTransaction (indexAtPosition (caretPos.getX(), caretPos.getY() - 1.0f), selecting);
  1546. }
  1547. bool TextEditor::moveCaretDown (bool selecting)
  1548. {
  1549. if (! isMultiLine())
  1550. return moveCaretToEndOfLine (selecting);
  1551. const Rectangle<float> caretPos (getCaretRectangle().toFloat());
  1552. return moveCaretWithTransaction (indexAtPosition (caretPos.getX(), caretPos.getBottom() + 1.0f), selecting);
  1553. }
  1554. bool TextEditor::pageUp (bool selecting)
  1555. {
  1556. if (! isMultiLine())
  1557. return moveCaretToStartOfLine (selecting);
  1558. const Rectangle<float> caretPos (getCaretRectangle().toFloat());
  1559. return moveCaretWithTransaction (indexAtPosition (caretPos.getX(), caretPos.getY() - viewport->getViewHeight()), selecting);
  1560. }
  1561. bool TextEditor::pageDown (bool selecting)
  1562. {
  1563. if (! isMultiLine())
  1564. return moveCaretToEndOfLine (selecting);
  1565. const Rectangle<float> caretPos (getCaretRectangle().toFloat());
  1566. return moveCaretWithTransaction (indexAtPosition (caretPos.getX(), caretPos.getBottom() + viewport->getViewHeight()), selecting);
  1567. }
  1568. void TextEditor::scrollByLines (int deltaLines)
  1569. {
  1570. if (ScrollBar* scrollbar = viewport->getVerticalScrollBar())
  1571. scrollbar->moveScrollbarInSteps (deltaLines);
  1572. }
  1573. bool TextEditor::scrollDown()
  1574. {
  1575. scrollByLines (-1);
  1576. return true;
  1577. }
  1578. bool TextEditor::scrollUp()
  1579. {
  1580. scrollByLines (1);
  1581. return true;
  1582. }
  1583. bool TextEditor::moveCaretToTop (bool selecting)
  1584. {
  1585. return moveCaretWithTransaction (0, selecting);
  1586. }
  1587. bool TextEditor::moveCaretToStartOfLine (bool selecting)
  1588. {
  1589. const Rectangle<float> caretPos (getCaretRectangle().toFloat());
  1590. return moveCaretWithTransaction (indexAtPosition (0.0f, caretPos.getY()), selecting);
  1591. }
  1592. bool TextEditor::moveCaretToEnd (bool selecting)
  1593. {
  1594. return moveCaretWithTransaction (getTotalNumChars(), selecting);
  1595. }
  1596. bool TextEditor::moveCaretToEndOfLine (bool selecting)
  1597. {
  1598. const Rectangle<float> caretPos (getCaretRectangle().toFloat());
  1599. return moveCaretWithTransaction (indexAtPosition ((float) textHolder->getWidth(), caretPos.getY()), selecting);
  1600. }
  1601. bool TextEditor::deleteBackwards (bool moveInWholeWordSteps)
  1602. {
  1603. if (moveInWholeWordSteps)
  1604. moveCaretTo (findWordBreakBefore (getCaretPosition()), true);
  1605. else if (selection.isEmpty() && selection.getStart() > 0)
  1606. selection.setStart (selection.getEnd() - 1);
  1607. cut();
  1608. return true;
  1609. }
  1610. bool TextEditor::deleteForwards (bool /*moveInWholeWordSteps*/)
  1611. {
  1612. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  1613. selection.setEnd (selection.getStart() + 1);
  1614. cut();
  1615. return true;
  1616. }
  1617. bool TextEditor::copyToClipboard()
  1618. {
  1619. newTransaction();
  1620. copy();
  1621. return true;
  1622. }
  1623. bool TextEditor::cutToClipboard()
  1624. {
  1625. newTransaction();
  1626. copy();
  1627. cut();
  1628. return true;
  1629. }
  1630. bool TextEditor::pasteFromClipboard()
  1631. {
  1632. newTransaction();
  1633. paste();
  1634. return true;
  1635. }
  1636. bool TextEditor::selectAll()
  1637. {
  1638. newTransaction();
  1639. moveCaretTo (getTotalNumChars(), false);
  1640. moveCaretTo (0, true);
  1641. return true;
  1642. }
  1643. //==============================================================================
  1644. void TextEditor::setEscapeAndReturnKeysConsumed (bool shouldBeConsumed) noexcept
  1645. {
  1646. consumeEscAndReturnKeys = shouldBeConsumed;
  1647. }
  1648. bool TextEditor::keyPressed (const KeyPress& key)
  1649. {
  1650. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  1651. return false;
  1652. if (! TextEditorKeyMapper<TextEditor>::invokeKeyFunction (*this, key))
  1653. {
  1654. if (key == KeyPress::returnKey)
  1655. {
  1656. newTransaction();
  1657. if (returnKeyStartsNewLine)
  1658. insertTextAtCaret ("\n");
  1659. else
  1660. {
  1661. returnPressed();
  1662. return consumeEscAndReturnKeys;
  1663. }
  1664. }
  1665. else if (key.isKeyCode (KeyPress::escapeKey))
  1666. {
  1667. newTransaction();
  1668. moveCaretTo (getCaretPosition(), false);
  1669. escapePressed();
  1670. return consumeEscAndReturnKeys;
  1671. }
  1672. else if (key.getTextCharacter() >= ' '
  1673. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  1674. {
  1675. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  1676. lastTransactionTime = Time::getApproximateMillisecondCounter();
  1677. }
  1678. else
  1679. {
  1680. return false;
  1681. }
  1682. }
  1683. return true;
  1684. }
  1685. bool TextEditor::keyStateChanged (const bool isKeyDown)
  1686. {
  1687. if (! isKeyDown)
  1688. return false;
  1689. #if JUCE_WINDOWS
  1690. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  1691. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  1692. #endif
  1693. if ((! consumeEscAndReturnKeys)
  1694. && (KeyPress (KeyPress::escapeKey).isCurrentlyDown()
  1695. || KeyPress (KeyPress::returnKey).isCurrentlyDown()))
  1696. return false;
  1697. // (overridden to avoid forwarding key events to the parent)
  1698. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  1699. }
  1700. //==============================================================================
  1701. void TextEditor::focusGained (FocusChangeType)
  1702. {
  1703. newTransaction();
  1704. if (selectAllTextWhenFocused)
  1705. {
  1706. moveCaretTo (0, false);
  1707. moveCaretTo (getTotalNumChars(), true);
  1708. }
  1709. repaint();
  1710. updateCaretPosition();
  1711. if (ComponentPeer* const peer = getPeer())
  1712. if (! isReadOnly())
  1713. peer->textInputRequired (peer->globalToLocal (getScreenPosition()));
  1714. }
  1715. void TextEditor::focusLost (FocusChangeType)
  1716. {
  1717. newTransaction();
  1718. wasFocused = false;
  1719. textHolder->stopTimer();
  1720. underlinedSections.clear();
  1721. if (ComponentPeer* const peer = getPeer())
  1722. peer->dismissPendingTextInput();
  1723. updateCaretPosition();
  1724. postCommandMessage (TextEditorDefs::focusLossMessageId);
  1725. repaint();
  1726. }
  1727. //==============================================================================
  1728. void TextEditor::resized()
  1729. {
  1730. viewport->setBoundsInset (borderSize);
  1731. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  1732. updateTextHolderSize();
  1733. if (isMultiLine())
  1734. updateCaretPosition();
  1735. else
  1736. scrollToMakeSureCursorIsVisible();
  1737. }
  1738. void TextEditor::handleCommandMessage (const int commandId)
  1739. {
  1740. Component::BailOutChecker checker (this);
  1741. switch (commandId)
  1742. {
  1743. case TextEditorDefs::textChangeMessageId:
  1744. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  1745. break;
  1746. case TextEditorDefs::returnKeyMessageId:
  1747. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  1748. break;
  1749. case TextEditorDefs::escapeKeyMessageId:
  1750. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  1751. break;
  1752. case TextEditorDefs::focusLossMessageId:
  1753. updateValueFromText();
  1754. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  1755. break;
  1756. default:
  1757. jassertfalse;
  1758. break;
  1759. }
  1760. }
  1761. void TextEditor::enablementChanged()
  1762. {
  1763. repaint();
  1764. }
  1765. void TextEditor::setTemporaryUnderlining (const Array <Range<int> >& newUnderlinedSections)
  1766. {
  1767. underlinedSections = newUnderlinedSections;
  1768. repaint();
  1769. }
  1770. //==============================================================================
  1771. UndoManager* TextEditor::getUndoManager() noexcept
  1772. {
  1773. return readOnly ? nullptr : &undoManager;
  1774. }
  1775. void TextEditor::clearInternal (UndoManager* const um)
  1776. {
  1777. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  1778. }
  1779. void TextEditor::insert (const String& text,
  1780. const int insertIndex,
  1781. const Font& font,
  1782. const Colour colour,
  1783. UndoManager* const um,
  1784. const int caretPositionToMoveTo)
  1785. {
  1786. if (text.isNotEmpty())
  1787. {
  1788. if (um != nullptr)
  1789. {
  1790. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  1791. newTransaction();
  1792. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  1793. caretPosition, caretPositionToMoveTo));
  1794. }
  1795. else
  1796. {
  1797. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  1798. // a line gets moved due to word wrap
  1799. int index = 0;
  1800. int nextIndex = 0;
  1801. for (int i = 0; i < sections.size(); ++i)
  1802. {
  1803. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  1804. if (insertIndex == index)
  1805. {
  1806. sections.insert (i, new UniformTextSection (text, font, colour, passwordCharacter));
  1807. break;
  1808. }
  1809. else if (insertIndex > index && insertIndex < nextIndex)
  1810. {
  1811. splitSection (i, insertIndex - index);
  1812. sections.insert (i + 1, new UniformTextSection (text, font, colour, passwordCharacter));
  1813. break;
  1814. }
  1815. index = nextIndex;
  1816. }
  1817. if (nextIndex == insertIndex)
  1818. sections.add (new UniformTextSection (text, font, colour, passwordCharacter));
  1819. coalesceSimilarSections();
  1820. totalNumChars = -1;
  1821. valueTextNeedsUpdating = true;
  1822. updateTextHolderSize();
  1823. moveCaretTo (caretPositionToMoveTo, false);
  1824. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  1825. }
  1826. }
  1827. }
  1828. void TextEditor::reinsert (const int insertIndex,
  1829. const Array <UniformTextSection*>& sectionsToInsert)
  1830. {
  1831. int index = 0;
  1832. int nextIndex = 0;
  1833. for (int i = 0; i < sections.size(); ++i)
  1834. {
  1835. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  1836. if (insertIndex == index)
  1837. {
  1838. for (int j = sectionsToInsert.size(); --j >= 0;)
  1839. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  1840. break;
  1841. }
  1842. else if (insertIndex > index && insertIndex < nextIndex)
  1843. {
  1844. splitSection (i, insertIndex - index);
  1845. for (int j = sectionsToInsert.size(); --j >= 0;)
  1846. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  1847. break;
  1848. }
  1849. index = nextIndex;
  1850. }
  1851. if (nextIndex == insertIndex)
  1852. {
  1853. for (int j = 0; j < sectionsToInsert.size(); ++j)
  1854. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  1855. }
  1856. coalesceSimilarSections();
  1857. totalNumChars = -1;
  1858. valueTextNeedsUpdating = true;
  1859. }
  1860. void TextEditor::remove (Range<int> range,
  1861. UndoManager* const um,
  1862. const int caretPositionToMoveTo)
  1863. {
  1864. if (! range.isEmpty())
  1865. {
  1866. int index = 0;
  1867. for (int i = 0; i < sections.size(); ++i)
  1868. {
  1869. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  1870. if (range.getStart() > index && range.getStart() < nextIndex)
  1871. {
  1872. splitSection (i, range.getStart() - index);
  1873. --i;
  1874. }
  1875. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  1876. {
  1877. splitSection (i, range.getEnd() - index);
  1878. --i;
  1879. }
  1880. else
  1881. {
  1882. index = nextIndex;
  1883. if (index > range.getEnd())
  1884. break;
  1885. }
  1886. }
  1887. index = 0;
  1888. if (um != nullptr)
  1889. {
  1890. Array <UniformTextSection*> removedSections;
  1891. for (int i = 0; i < sections.size(); ++i)
  1892. {
  1893. if (range.getEnd() <= range.getStart())
  1894. break;
  1895. UniformTextSection* const section = sections.getUnchecked (i);
  1896. const int nextIndex = index + section->getTotalLength();
  1897. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  1898. removedSections.add (new UniformTextSection (*section));
  1899. index = nextIndex;
  1900. }
  1901. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  1902. newTransaction();
  1903. um->perform (new RemoveAction (*this, range, caretPosition,
  1904. caretPositionToMoveTo, removedSections));
  1905. }
  1906. else
  1907. {
  1908. Range<int> remainingRange (range);
  1909. for (int i = 0; i < sections.size(); ++i)
  1910. {
  1911. UniformTextSection* const section = sections.getUnchecked (i);
  1912. const int nextIndex = index + section->getTotalLength();
  1913. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  1914. {
  1915. sections.remove(i);
  1916. section->clear();
  1917. delete section;
  1918. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  1919. if (remainingRange.isEmpty())
  1920. break;
  1921. --i;
  1922. }
  1923. else
  1924. {
  1925. index = nextIndex;
  1926. }
  1927. }
  1928. coalesceSimilarSections();
  1929. totalNumChars = -1;
  1930. valueTextNeedsUpdating = true;
  1931. moveCaretTo (caretPositionToMoveTo, false);
  1932. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  1933. }
  1934. }
  1935. }
  1936. //==============================================================================
  1937. String TextEditor::getText() const
  1938. {
  1939. MemoryOutputStream mo;
  1940. mo.preallocate ((size_t) getTotalNumChars());
  1941. for (int i = 0; i < sections.size(); ++i)
  1942. sections.getUnchecked (i)->appendAllText (mo);
  1943. return mo.toUTF8();
  1944. }
  1945. String TextEditor::getTextInRange (const Range<int>& range) const
  1946. {
  1947. if (range.isEmpty())
  1948. return String::empty;
  1949. MemoryOutputStream mo;
  1950. mo.preallocate ((size_t) jmin (getTotalNumChars(), range.getLength()));
  1951. int index = 0;
  1952. for (int i = 0; i < sections.size(); ++i)
  1953. {
  1954. const UniformTextSection* const s = sections.getUnchecked (i);
  1955. const int nextIndex = index + s->getTotalLength();
  1956. if (range.getStart() < nextIndex)
  1957. {
  1958. if (range.getEnd() <= index)
  1959. break;
  1960. s->appendSubstring (mo, range - index);
  1961. }
  1962. index = nextIndex;
  1963. }
  1964. return mo.toUTF8();
  1965. }
  1966. String TextEditor::getHighlightedText() const
  1967. {
  1968. return getTextInRange (selection);
  1969. }
  1970. int TextEditor::getTotalNumChars() const
  1971. {
  1972. if (totalNumChars < 0)
  1973. {
  1974. totalNumChars = 0;
  1975. for (int i = sections.size(); --i >= 0;)
  1976. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  1977. }
  1978. return totalNumChars;
  1979. }
  1980. bool TextEditor::isEmpty() const
  1981. {
  1982. return getTotalNumChars() == 0;
  1983. }
  1984. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  1985. {
  1986. const float wordWrapWidth = getWordWrapWidth();
  1987. if (wordWrapWidth > 0 && sections.size() > 0)
  1988. {
  1989. Iterator i (sections, wordWrapWidth, passwordCharacter);
  1990. i.getCharPosition (index, cx, cy, lineHeight);
  1991. }
  1992. else
  1993. {
  1994. cx = cy = 0;
  1995. lineHeight = currentFont.getHeight();
  1996. }
  1997. }
  1998. int TextEditor::indexAtPosition (const float x, const float y)
  1999. {
  2000. const float wordWrapWidth = getWordWrapWidth();
  2001. if (wordWrapWidth > 0)
  2002. {
  2003. Iterator i (sections, wordWrapWidth, passwordCharacter);
  2004. while (i.next())
  2005. {
  2006. if (i.lineY + i.lineHeight > y)
  2007. {
  2008. if (i.lineY > y)
  2009. return jmax (0, i.indexInText - 1);
  2010. if (i.atomX >= x)
  2011. return i.indexInText;
  2012. if (x < i.atomRight)
  2013. return i.xToIndex (x);
  2014. }
  2015. }
  2016. }
  2017. return getTotalNumChars();
  2018. }
  2019. //==============================================================================
  2020. int TextEditor::findWordBreakAfter (const int position) const
  2021. {
  2022. const String t (getTextInRange (Range<int> (position, position + 512)));
  2023. const int totalLength = t.length();
  2024. int i = 0;
  2025. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  2026. ++i;
  2027. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  2028. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  2029. ++i;
  2030. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  2031. ++i;
  2032. return position + i;
  2033. }
  2034. int TextEditor::findWordBreakBefore (const int position) const
  2035. {
  2036. if (position <= 0)
  2037. return 0;
  2038. const int startOfBuffer = jmax (0, position - 512);
  2039. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  2040. int i = position - startOfBuffer;
  2041. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  2042. --i;
  2043. if (i > 0)
  2044. {
  2045. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  2046. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  2047. --i;
  2048. }
  2049. jassert (startOfBuffer + i >= 0);
  2050. return startOfBuffer + i;
  2051. }
  2052. //==============================================================================
  2053. void TextEditor::splitSection (const int sectionIndex,
  2054. const int charToSplitAt)
  2055. {
  2056. jassert (sections[sectionIndex] != nullptr);
  2057. sections.insert (sectionIndex + 1,
  2058. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  2059. }
  2060. void TextEditor::coalesceSimilarSections()
  2061. {
  2062. for (int i = 0; i < sections.size() - 1; ++i)
  2063. {
  2064. UniformTextSection* const s1 = sections.getUnchecked (i);
  2065. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  2066. if (s1->font == s2->font
  2067. && s1->colour == s2->colour)
  2068. {
  2069. s1->append (*s2, passwordCharacter);
  2070. sections.remove (i + 1);
  2071. delete s2;
  2072. --i;
  2073. }
  2074. }
  2075. }