├── .clang-format
├── .gitignore
├── CMakeLists.txt
├── LICENSE
├── README.md
├── lib
├── CMakeLists.txt
├── public
│ ├── controllers
│ │ ├── editor-controller.h
│ │ ├── file-navigation-controller.h
│ │ ├── main-controller.h
│ │ └── menu-controller.h
│ ├── document-handler.h
│ ├── file-handler.h
│ ├── globals.h
│ └── models
│ │ ├── abstract-editor-model.h
│ │ ├── documents-model.h
│ │ ├── editor-model.h
│ │ ├── file-navigation-model.h
│ │ └── menu-model.h
├── src
│ ├── controllers
│ │ ├── editor-controller.cpp
│ │ ├── file-navigation-controller.cpp
│ │ ├── main-controller.cpp
│ │ └── menu-controller.cpp
│ ├── document-handler.cpp
│ ├── file-handler.cpp
│ └── models
│ │ ├── abstract-editor-model.cpp
│ │ ├── documents-model.cpp
│ │ ├── editor-model.cpp
│ │ ├── file-navigation-model.cpp
│ │ └── menu-model.cpp
└── tests
│ ├── CMakeLists.txt
│ └── src
│ ├── document-handler-tests.cpp
│ ├── document-handler-tests.h
│ ├── documents-model-tests.cpp
│ ├── documents-model-tests.h
│ ├── file-handler-tests.cpp
│ ├── file-handler-tests.h
│ ├── main.cpp
│ ├── test-runner.cpp
│ └── test-runner.h
├── screencapture.png
└── ui-qml
├── CMakeLists.txt
├── components
├── EditorComponent.qml
├── FileNavigationComponent.qml
├── MenuComponent.qml
└── qmldir
├── fonts
├── Hack-Bold.ttf
├── Hack-BoldItalic.ttf
├── Hack-Italic.ttf
├── Hack-Regular.ttf
└── fontello.ttf
├── qtquickcontrols2.conf
├── resources.qrc
├── src
├── line-numbers.cpp
├── line-numbers.h
├── main.cpp
├── qml-editor-model.cpp
└── qml-editor-model.h
├── styles
├── MenuToolButton.qml
├── Style.qml
└── qmldir
└── views
└── MainView.qml
/.clang-format:
--------------------------------------------------------------------------------
1 | # Pretty much same as QtCreator's format:
2 | # https://github.com/qt-creator/qt-creator/blob/master/.clang-format
3 |
4 | Language: Cpp
5 | AccessModifierOffset: -4
6 | AlignAfterOpenBracket: Align
7 | AlignConsecutiveAssignments: false
8 | AlignConsecutiveDeclarations: false
9 | AlignEscapedNewlines: DontAlign
10 | AlignOperands: true
11 | AlignTrailingComments: true
12 | AllowAllParametersOfDeclarationOnNextLine: true
13 | AllowShortBlocksOnASingleLine: false
14 | AllowShortCaseLabelsOnASingleLine: false
15 | AllowShortFunctionsOnASingleLine: Inline
16 | AllowShortIfStatementsOnASingleLine: false
17 | AllowShortLoopsOnASingleLine: false
18 | AlwaysBreakAfterReturnType: None
19 | AlwaysBreakBeforeMultilineStrings: false
20 | AlwaysBreakTemplateDeclarations: true
21 | BinPackArguments: false
22 | BinPackParameters: false
23 | BraceWrapping:
24 | AfterClass: true
25 | AfterControlStatement: false
26 | AfterEnum: false
27 | AfterFunction: true
28 | AfterNamespace: false
29 | AfterObjCDeclaration: false
30 | AfterStruct: true
31 | AfterUnion: false
32 | BeforeCatch: false
33 | BeforeElse: false
34 | IndentBraces: false
35 | SplitEmptyFunction: false
36 | SplitEmptyRecord: false
37 | SplitEmptyNamespace: false
38 | BreakBeforeBinaryOperators: All
39 | BreakBeforeBraces: Custom
40 | BreakBeforeInheritanceComma: false
41 | BreakBeforeTernaryOperators: true
42 | BreakConstructorInitializersBeforeComma: false
43 | BreakConstructorInitializers: BeforeComma
44 | BreakAfterJavaFieldAnnotations: false
45 | BreakStringLiterals: true
46 | ColumnLimit: 100
47 | CommentPragmas: '^ IWYU pragma:'
48 | CompactNamespaces: false
49 | ConstructorInitializerAllOnOneLineOrOnePerLine: false
50 | ConstructorInitializerIndentWidth: 4
51 | ContinuationIndentWidth: 4
52 | Cpp11BracedListStyle: true
53 | DerivePointerAlignment: false
54 | DisableFormat: false
55 | ExperimentalAutoDetectBinPacking: false
56 | FixNamespaceComments: true
57 | ForEachMacros:
58 | - forever # avoids { wrapped to next line
59 | - foreach
60 | - Q_FOREACH
61 | - BOOST_FOREACH
62 | IncludeCategories:
63 | - Regex: '^
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Clean Editor
2 |
3 |
4 | A simple code editor using Qt Qml/Quick and Widgets front-ends
5 |
6 |
7 |
8 | ## Description
9 |
10 | Sample project that demonstrates how to structure a Qt example with two front-ends sharing the same back-end. The two front-ends use different Qt technologies: Qt Widgets as well as Qt Quick/QML. Currently only the QML front-end has been implemented.
11 |
12 | The project is a simple code editor, where it's possible to open and edit files.
13 |
14 | Further details of the project can be found on my blog www.cleanqt.io, where it's thoroughly covered in the [Crash Course for C++ developers series](https://www.cleanqt.io/blog/crash-course-in-qt-for-c%2B%2B-developers,-part-7).
15 |
16 | ## Building
17 |
18 | These are the instructions on how to build the sample application using the CMake buildsystem generator.
19 |
20 | The project requires:
21 | * `CMake version >= 3.8.2`
22 | * `Qt version >= 6.0` with `Core`, `Gui`, `Qml`, `Quick`, `QuickControls2` enabled and `C++17` compiler.
23 |
24 | ### Instructions
25 |
26 | 1. From the root directory of the checkout, create a build directory and change into it:
27 |
28 | ```
29 | mkdir build
30 | cd build
31 | ```
32 |
33 | 2. Generate the desired project by using `cmake`. Specify the generator with the `-G` option. See `cmake --help` for more information. Example using default generator and debug build:
34 |
35 | ```
36 | cmake -DCMAKE_PREFIX_PATH=/qt6/install/path -DCMAKE_BUILD_TYPE=Debug ..
37 | ```
38 |
39 | 3. Build by running either of the following commands:
40 | ```
41 | make # Unix,
42 | nmake # Windows
43 | ```
44 |
45 | Alternatively, if you're using Qt Creator, just open up the `CMakeLists.txt` in the root directory.
46 |
--------------------------------------------------------------------------------
/lib/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.8.2)
2 | cmake_policy(SET CMP0048 NEW)
3 | project(clean-editor-lib VERSION 1.0.0 LANGUAGES C CXX)
4 |
5 | ###########################
6 | # Dependencies
7 | find_package(Qt6 COMPONENTS Core Gui REQUIRED)
8 |
9 | ###########################
10 | # Targets
11 | add_library(${PROJECT_NAME} SHARED
12 | # Src
13 | ## Controllers
14 | src/controllers/main-controller.cpp
15 | src/controllers/file-navigation-controller.cpp
16 | src/controllers/editor-controller.cpp
17 | src/controllers/menu-controller.cpp
18 |
19 | ## Models
20 | src/models/documents-model.cpp
21 | src/models/editor-model.cpp
22 | src/models/abstract-editor-model.cpp
23 | src/models/menu-model.cpp
24 | src/models/file-navigation-model.cpp
25 |
26 | src/file-handler.cpp
27 | src/document-handler.cpp
28 |
29 | # Public
30 | ## Controllers
31 | public/controllers/main-controller.h
32 | public/controllers/file-navigation-controller.h
33 | public/controllers/editor-controller.h
34 | public/controllers/menu-controller.h
35 |
36 | ## Models
37 | public/models/documents-model.h
38 | public/models/editor-model.h
39 | public/models/abstract-editor-model.h
40 | public/models/menu-model.h
41 | public/models/file-navigation-model.h
42 |
43 | public/globals.h
44 | public/file-handler.h
45 | public/document-handler.h
46 | )
47 |
48 | target_include_directories(${PROJECT_NAME}
49 | PUBLIC
50 | $
55 | $
60 | PRIVATE
61 | ${CMAKE_CURRENT_SOURCE_DIR}/src
62 | ${CMAKE_CURRENT_SOURCE_DIR}/src/controllers
63 | ${CMAKE_CURRENT_SOURCE_DIR}/src/models
64 | )
65 |
66 | target_compile_definitions(${PROJECT_NAME}
67 | PRIVATE
68 | CLEAN_EDITOR_LIBRARY
69 | )
70 |
71 | target_link_libraries(${PROJECT_NAME}
72 | PUBLIC
73 | Qt6::Core
74 | Qt6::Gui
75 | )
76 |
77 | target_compile_features(${PROJECT_NAME}
78 | PUBLIC
79 | cxx_std_17
80 | )
81 |
82 | set_target_properties(${PROJECT_NAME}
83 | PROPERTIES
84 | AUTOMOC ON
85 | ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
86 | LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
87 | RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
88 | )
89 |
90 | ###########################
91 | # Include tests
92 |
93 | add_subdirectory(tests)
94 |
--------------------------------------------------------------------------------
/lib/public/controllers/editor-controller.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 |
6 | #include "globals.h"
7 |
8 | namespace CleanEditor {
9 | namespace Models {
10 | class AbstractEditorModel;
11 | }
12 |
13 | namespace Controllers {
14 |
15 | /*!
16 | * \brief The EditorController class is the router that passes data onto the model.
17 | * The class also recieves user input directly from a corresponding view (using the signals).
18 | *
19 | * \sa AbstractEditorModel
20 | */
21 | class CLEAN_EDITOR_EXPORT EditorController : public QObject
22 | {
23 | Q_OBJECT
24 | Q_DISABLE_COPY_MOVE(EditorController)
25 |
26 | public:
27 | explicit EditorController(QObject *parent = nullptr);
28 |
29 | void setModel(CleanEditor::Models::AbstractEditorModel &model);
30 |
31 | QString text() const;
32 | void setText(const QString &text);
33 |
34 | int id() const;
35 | void setId(int id);
36 |
37 | Q_SIGNALS:
38 | void textChanged();
39 |
40 | private:
41 | CleanEditor::Models::AbstractEditorModel *model_{nullptr};
42 | QMetaObject::Connection text_changed_connection_;
43 | };
44 |
45 | } // namespace Controllers
46 | } // namespace CleanEditor
47 |
--------------------------------------------------------------------------------
/lib/public/controllers/file-navigation-controller.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 |
5 | #include "globals.h"
6 |
7 | namespace CleanEditor {
8 | namespace Models {
9 | class FileNavigationModel;
10 | }
11 | namespace Controllers {
12 |
13 | class CLEAN_EDITOR_EXPORT FileNavigationController : public QObject
14 | {
15 | Q_OBJECT
16 | Q_DISABLE_COPY_MOVE(FileNavigationController)
17 |
18 | public:
19 | explicit FileNavigationController(QObject *parent = nullptr);
20 |
21 | void setModel(CleanEditor::Models::FileNavigationModel &model);
22 |
23 | int selectedIndex() const;
24 | void setSelectedIndex(int index);
25 |
26 | Q_SIGNALS:
27 | void fileOpenedClicked(int id);
28 |
29 | private:
30 | CleanEditor::Models::FileNavigationModel *model_{nullptr};
31 | };
32 |
33 | } // namespace Controllers
34 | } // namespace CleanEditor
35 |
--------------------------------------------------------------------------------
/lib/public/controllers/main-controller.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 |
6 | #include "editor-controller.h"
7 | #include "file-navigation-controller.h"
8 | #include "menu-controller.h"
9 |
10 | #include "globals.h"
11 |
12 | namespace CleanEditor {
13 | namespace Models {
14 | class DocumentsModel;
15 | }
16 |
17 | namespace Controllers {
18 |
19 | class CLEAN_EDITOR_EXPORT MainController : public QObject
20 | {
21 | Q_OBJECT
22 | Q_DISABLE_COPY_MOVE(MainController)
23 |
24 | Q_PROPERTY(CleanEditor::Controllers::MenuController *menuController READ menuController CONSTANT)
25 | Q_PROPERTY(
26 | CleanEditor::Controllers::EditorController *editorController READ editorController CONSTANT)
27 | Q_PROPERTY(CleanEditor::Controllers::FileNavigationController *fileNavigationController READ
28 | fileNavigationController CONSTANT)
29 |
30 | public:
31 | explicit MainController(QObject *parent = nullptr);
32 |
33 | void setDocumentsModel(CleanEditor::Models::DocumentsModel &documents_model);
34 |
35 | MenuController *menuController();
36 | EditorController *editorController();
37 | FileNavigationController *fileNavigationController();
38 |
39 | private:
40 | void storeTextToCurrentFile();
41 |
42 | MenuController menu_controller_;
43 | EditorController editor_controller_;
44 | FileNavigationController file_navigation_controller_;
45 | CleanEditor::Models::DocumentsModel *documents_model_{nullptr};
46 | QMetaObject::Connection document_created_connection_;
47 |
48 | private Q_SLOTS:
49 | void handleEditorTextChanged();
50 | void openDocument(int id);
51 | void handleSaveFileClicked();
52 | void handleSaveAsFileClicked(const QUrl &url);
53 | void handleNewFileClicked();
54 | void handleOpenedFileClicked(int id);
55 | void handleOpenFileClicked(const QUrl &url);
56 | };
57 |
58 | } // namespace Controllers
59 | } // namespace CleanEditor
60 |
--------------------------------------------------------------------------------
/lib/public/controllers/menu-controller.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 |
5 | #include "globals.h"
6 |
7 | namespace CleanEditor {
8 | namespace Models {
9 | class MenuModel;
10 | }
11 | namespace Logic {
12 | class DocumentHandler;
13 | }
14 |
15 | namespace Controllers {
16 |
17 | class CLEAN_EDITOR_EXPORT MenuController : public QObject
18 | {
19 | Q_OBJECT
20 | Q_DISABLE_COPY_MOVE(MenuController)
21 |
22 | public:
23 | explicit MenuController(QObject *parent = nullptr);
24 |
25 | void setModel(CleanEditor::Models::MenuModel &model);
26 |
27 | void setDocument(CleanEditor::Logic::DocumentHandler &document_handler);
28 |
29 | Q_SIGNALS:
30 | void newFileClicked();
31 | void openFileClicked(const QUrl &file_url);
32 | void saveFileClicked();
33 | void saveAsFileClicked(const QUrl &file_url);
34 |
35 | private:
36 | CleanEditor::Models::MenuModel *model_{nullptr};
37 | };
38 |
39 | } // namespace Controllers
40 | } // namespace CleanEditor
41 |
--------------------------------------------------------------------------------
/lib/public/document-handler.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 | #include
6 | #include
7 |
8 | #include "file-handler.h"
9 |
10 | #include "globals.h"
11 |
12 | class QTextDocument;
13 | class QQuickTextDocument;
14 |
15 | namespace CleanEditor::Logic {
16 | /*!
17 | * \brief The DocumentHandler class handles a document that has been opened or is newly created.
18 | *
19 | * A newly created DocumentHandler is automatically considered a new file until load() or
20 | * saveAs() is called. An id is generated automatically.
21 | *
22 | * The document can be flagged as 'needsUpdating' which needs to be set in order to update
23 | * the content using setContent().
24 | *
25 | * needsSaving is automatically set when the content has been updated but not saved.
26 | *
27 | * filename and fileType are parsed from the fileUrl.
28 | *
29 | * \sa FileHandler
30 | *
31 | */
32 | class CLEAN_EDITOR_EXPORT DocumentHandler : public QObject
33 | {
34 | Q_OBJECT
35 | Q_DISABLE_COPY_MOVE(DocumentHandler)
36 |
37 | Q_PROPERTY(QString filename READ filename)
38 | Q_PROPERTY(QString fileType READ fileType)
39 | Q_PROPERTY(QUrl fileUrl READ fileUrl NOTIFY fileUrlChanged)
40 | Q_PROPERTY(QString textContent READ textContent WRITE setTextContent)
41 | Q_PROPERTY(int id READ id)
42 | Q_PROPERTY(
43 | bool needsUpdating READ needsUpdating WRITE setNeedsUpdating NOTIFY needsUpdatingChanged)
44 | Q_PROPERTY(bool needsSaving READ needsSaving WRITE setNeedsSaving NOTIFY needsSavingChanged)
45 | Q_PROPERTY(bool isNewFile READ isNewFile WRITE setIsNewFile NOTIFY isNewFileChanged)
46 |
47 | public:
48 | explicit DocumentHandler(QObject *parent = nullptr);
49 |
50 | QString filename() const;
51 | QString fileType() const;
52 | QUrl fileUrl() const;
53 | QString textContent() const;
54 | int id() const;
55 |
56 | bool needsUpdating() const;
57 | void setNeedsUpdating(bool needs_updating);
58 |
59 | bool needsSaving() const;
60 |
61 | bool isNewFile() const;
62 |
63 | public Q_SLOTS:
64 | void load(const QUrl &file_url);
65 | void saveAs(const QUrl &file_url);
66 | void save();
67 | void setTextContent(const QString &text);
68 |
69 | Q_SIGNALS:
70 | void fileUrlChanged();
71 | void fileOpened();
72 | void error(const QString &message);
73 | void contentUpdated();
74 | void needsUpdatingChanged();
75 | void isNewFileChanged();
76 | void needsSavingChanged();
77 |
78 | private:
79 | void setIsNewFile(bool new_file);
80 | void setNeedsSaving(bool needs_saving);
81 |
82 | int id_{0};
83 | FileHandler file_handler_;
84 | QString text_content_;
85 | bool needs_updating_{false};
86 | bool is_new_file_{true};
87 | bool needs_saving_{false};
88 |
89 | private Q_SLOTS:
90 | void onFileOpened();
91 | };
92 |
93 | } //namespace CleanEditor::Logic
94 |
95 | Q_DECLARE_METATYPE(CleanEditor::Logic::DocumentHandler *)
96 |
--------------------------------------------------------------------------------
/lib/public/file-handler.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 | #include
6 |
7 | #include "globals.h"
8 |
9 | namespace CleanEditor::Logic {
10 |
11 | class CLEAN_EDITOR_EXPORT FileHandler : public QObject
12 | {
13 | Q_OBJECT
14 | Q_DISABLE_COPY_MOVE(FileHandler)
15 |
16 | Q_PROPERTY(QString fileName READ fileName NOTIFY fileUrlChanged)
17 | Q_PROPERTY(QString fileType READ fileType NOTIFY fileUrlChanged)
18 | Q_PROPERTY(QUrl fileUrl READ fileUrl NOTIFY fileUrlChanged)
19 | Q_PROPERTY(QString data READ data)
20 |
21 | public:
22 | explicit FileHandler(QObject *parent = nullptr);
23 |
24 | QString fileName() const;
25 | QString fileType() const;
26 | QUrl fileUrl() const;
27 | QString data() const;
28 |
29 | public Q_SLOTS:
30 | void load(const QUrl &file_url);
31 | bool saveAs(const QUrl &file_url, const QString &data);
32 | bool save(const QString &data);
33 |
34 | Q_SIGNALS:
35 | void fileUrlChanged();
36 | void fileOpened();
37 | void error(const QString &message);
38 |
39 | private:
40 | QUrl file_url_;
41 | static QString localPathFromUrl(const QUrl &file_url);
42 | };
43 |
44 | } //namespace CleanEditor::Logic
45 |
--------------------------------------------------------------------------------
/lib/public/globals.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 |
5 | #if defined(CLEAN_EDITOR_LIBRARY)
6 | #define CLEAN_EDITOR_EXPORT Q_DECL_EXPORT
7 | #else
8 | #define CLEAN_EDITOR_EXPORT Q_DECL_IMPORT
9 | #endif
10 |
--------------------------------------------------------------------------------
/lib/public/models/abstract-editor-model.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 |
6 | #include "globals.h"
7 |
8 | class QTextDocument;
9 |
10 | namespace CleanEditor::Models {
11 |
12 | /*!
13 | * \brief The AbstractEditorModel class defines an abstract class that wraps around
14 | * data and functionality and is used in a text editor.
15 | *
16 | * text() and setText() needs to be overridden. When the text has been replaced (i.e. when
17 | * setText is called), textReplaced needs to be emitted.
18 | *
19 | * id_ (id() and setId) is used to identify the currently opened document that's being edited.
20 | */
21 | class CLEAN_EDITOR_EXPORT AbstractEditorModel : public QObject
22 | {
23 | Q_OBJECT
24 | Q_DISABLE_COPY_MOVE(AbstractEditorModel)
25 |
26 | Q_PROPERTY(QString text READ text WRITE setText NOTIFY textReplaced)
27 | Q_PROPERTY(int id READ id WRITE setId NOTIFY idChanged)
28 |
29 | public:
30 | explicit AbstractEditorModel(QObject *parent = nullptr);
31 |
32 | virtual QString text() const = 0;
33 | virtual void setText(const QString &text) = 0;
34 |
35 | int id() const;
36 | void setId(int id);
37 |
38 | Q_SIGNALS:
39 | //! Used when the a minor change has been made in the text
40 | void textChanged();
41 |
42 | //! Used when setText is called (and therefore replaced).
43 | void textReplaced();
44 | void idChanged();
45 |
46 | private:
47 | int id_{0};
48 | };
49 |
50 | } // namespace CleanEditor::Models
51 |
--------------------------------------------------------------------------------
/lib/public/models/documents-model.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 |
6 | #include
7 | #include
8 | #include
9 |
10 | #include "document-handler.h"
11 | #include "globals.h"
12 |
13 | namespace CleanEditor {
14 |
15 | namespace Logic {
16 | class DocumentHandler;
17 | }
18 |
19 | namespace Models {
20 |
21 | /*!
22 | * \brief The DocumentsModel class is a Qt List Model and can be shown using a Qt View.
23 | * The class wraps around a list of DocumentHandlers (Documents).
24 | *
25 | * A new document is created by calling newFile() or openFile(), which will then signal
26 | * documentCreated(), including a document ID.
27 | *
28 | * The ID is used to GET specific data from the document using one of the getters.
29 | * Or, likewise, the ID can be used to SET specific data for the document using one
30 | * of the setters.
31 | *
32 | * \sa DocumentHandler
33 | */
34 | class CLEAN_EDITOR_EXPORT DocumentsModel : public QAbstractListModel
35 | {
36 | Q_OBJECT
37 | Q_DISABLE_COPY_MOVE(DocumentsModel)
38 |
39 | public:
40 | enum DocumentsRoles {
41 | FileIdRole = Qt::UserRole + 1,
42 | FileDocumentRole,
43 | FilenameRole,
44 | FileTypeRole,
45 | FileUrlRole,
46 | FileContentRole,
47 | FileNeedsUpdatingRole,
48 | FileNeedsSavingRole,
49 | FileIsNewRole,
50 | };
51 |
52 | explicit DocumentsModel(QObject *parent = nullptr);
53 |
54 | int rowCount(const QModelIndex &parent = QModelIndex()) const override;
55 | QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
56 | QHash roleNames() const override;
57 |
58 | CleanEditor::Logic::DocumentHandler *document(int id) const;
59 |
60 | QString filename(int id) const;
61 | QString fileType(int id) const;
62 | QUrl fileUrl(int id) const;
63 | bool isFileNew(int id) const;
64 |
65 | bool needsUpdating(int id) const;
66 | bool needsSaving(int id) const;
67 |
68 | QString fileContent(int id) const;
69 | void setFileContent(int id, const QString &text);
70 |
71 | void save(int id);
72 | void saveAs(int id, const QUrl &file_url);
73 |
74 | void setNeedsUpdating(int id);
75 |
76 | QModelIndex indexForId(int id) const;
77 |
78 | public Q_SLOTS:
79 | void newFile();
80 | void openFile(const QUrl &file_url);
81 | void closeFile(int id);
82 |
83 | Q_SIGNALS:
84 | void documentCreated(int id);
85 |
86 | private:
87 | std::vector> data_;
88 |
89 | void appendNewDocument(std::unique_ptr document);
90 |
91 | template
92 | T getData(const int id, const DocumentsRoles role, const T &default_value) const
93 | {
94 | const auto index = indexForId(id);
95 | if (!index.isValid()) {
96 | return default_value;
97 | }
98 |
99 | return data(index, role).value();
100 | }
101 |
102 | template
103 | void setData(const int id, const TFunc function, Values &&... values)
104 | {
105 | for (size_t i{0}; i < data_.size(); i++) {
106 | if (data_.at(i)->id() == id) {
107 | std::bind(function, data_.at(i).get(), std::forward(values)...)();
108 | auto model_index = index(static_cast(i), 0);
109 | emit dataChanged(model_index, model_index);
110 | return;
111 | }
112 | }
113 | }
114 | };
115 |
116 | } //namespace Models
117 | } //namespace CleanEditor
118 |
--------------------------------------------------------------------------------
/lib/public/models/editor-model.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "abstract-editor-model.h"
4 | #include "globals.h"
5 |
6 | #include
7 |
8 | class QTextDocument;
9 |
10 | namespace CleanEditor::Models {
11 | class CLEAN_EDITOR_EXPORT EditorModel : public AbstractEditorModel
12 | {
13 | Q_OBJECT
14 | Q_DISABLE_COPY_MOVE(EditorModel)
15 |
16 | public:
17 | explicit EditorModel(QObject *parent = nullptr);
18 |
19 | QString text() const override;
20 | void setText(const QString &text) override;
21 |
22 | void setTextDocument(QTextDocument *text_document);
23 |
24 | private:
25 | QTextDocument *text_document_{nullptr};
26 | };
27 |
28 | } // namespace CleanEditor::Models
29 |
--------------------------------------------------------------------------------
/lib/public/models/file-navigation-model.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "globals.h"
4 |
5 | #include
6 |
7 | namespace CleanEditor::Models {
8 |
9 | class CLEAN_EDITOR_EXPORT FileNavigationModel : public QObject
10 | {
11 | Q_OBJECT
12 | Q_DISABLE_COPY_MOVE(FileNavigationModel)
13 |
14 | Q_PROPERTY(
15 | int selectedIndex READ selectedIndex WRITE setSelectedIndex NOTIFY selectedIndexChanged)
16 |
17 | public:
18 | explicit FileNavigationModel(QObject *parent = nullptr);
19 |
20 | int selectedIndex() const;
21 | void setSelectedIndex(int index);
22 |
23 | Q_SIGNALS:
24 | void selectedIndexChanged();
25 |
26 | private:
27 | int selected_index_{-1};
28 | };
29 |
30 | } // namespace CleanEditor::Models
31 |
--------------------------------------------------------------------------------
/lib/public/models/menu-model.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "globals.h"
4 |
5 | #include
6 | #include
7 | #include
8 |
9 | class QTextDocument;
10 |
11 | namespace CleanEditor {
12 | namespace Logic {
13 | class DocumentHandler;
14 | }
15 | namespace Models {
16 |
17 | class CLEAN_EDITOR_EXPORT MenuModel : public QObject
18 | {
19 | Q_OBJECT
20 | Q_DISABLE_COPY_MOVE(MenuModel)
21 |
22 | Q_PROPERTY(QString title READ title NOTIFY titleChanged)
23 | Q_PROPERTY(bool isNewFile READ isNewFile NOTIFY isNewFileChanged)
24 |
25 | public:
26 | explicit MenuModel(QObject *parent = nullptr);
27 |
28 | void setDocument(CleanEditor::Logic::DocumentHandler &document_handler);
29 |
30 | QString title() const;
31 | bool isNewFile() const;
32 |
33 | Q_SIGNALS:
34 | void titleChanged();
35 | void isNewFileChanged();
36 |
37 | private:
38 | QPointer document_handler_;
39 | };
40 |
41 | } // namespace Models
42 | } // namespace CleanEditor
43 |
--------------------------------------------------------------------------------
/lib/src/controllers/editor-controller.cpp:
--------------------------------------------------------------------------------
1 | #include "editor-controller.h"
2 |
3 | #include "editor-model.h"
4 |
5 | using namespace CleanEditor::Models;
6 |
7 | namespace CleanEditor::Controllers {
8 |
9 | EditorController::EditorController(QObject *parent)
10 | : QObject{parent}
11 | {}
12 |
13 | void EditorController::setModel(AbstractEditorModel &model)
14 | {
15 | disconnect(text_changed_connection_);
16 | model_ = &model;
17 | text_changed_connection_ = connect(model_,
18 | &AbstractEditorModel::textChanged,
19 | this,
20 | &EditorController::textChanged);
21 | }
22 |
23 | QString EditorController::text() const
24 | {
25 | if (!model_) {
26 | return "";
27 | }
28 |
29 | return model_->text();
30 | }
31 | void EditorController::setText(const QString &text)
32 | {
33 | if (!model_) {
34 | return;
35 | }
36 |
37 | model_->setText(text);
38 | }
39 |
40 | int EditorController::id() const
41 | {
42 | if (!model_) {
43 | return 0;
44 | }
45 |
46 | return model_->id();
47 | }
48 |
49 | void EditorController::setId(const int id)
50 | {
51 | if (!model_) {
52 | return;
53 | }
54 |
55 | model_->setId(id);
56 | }
57 |
58 | } // namespace CleanEditor::Controllers
59 |
--------------------------------------------------------------------------------
/lib/src/controllers/file-navigation-controller.cpp:
--------------------------------------------------------------------------------
1 | #include "file-navigation-controller.h"
2 | #include "file-navigation-model.h"
3 |
4 | namespace CleanEditor::Controllers {
5 |
6 | FileNavigationController::FileNavigationController(QObject *parent)
7 | : QObject{parent}
8 | {}
9 |
10 | void FileNavigationController::setModel(CleanEditor::Models::FileNavigationModel &model)
11 | {
12 | model_ = &model;
13 | }
14 |
15 | int FileNavigationController::selectedIndex() const
16 | {
17 | if (!model_) {
18 | return -1;
19 | }
20 |
21 | return model_->selectedIndex();
22 | }
23 |
24 | void FileNavigationController::setSelectedIndex(const int index)
25 | {
26 | if (!model_) {
27 | return;
28 | }
29 |
30 | model_->setSelectedIndex(index);
31 | }
32 |
33 | } // namespace CleanEditor::Controllers
34 |
--------------------------------------------------------------------------------
/lib/src/controllers/main-controller.cpp:
--------------------------------------------------------------------------------
1 | #include "main-controller.h"
2 |
3 | #include "editor-controller.h"
4 | #include "file-navigation-controller.h"
5 | #include "menu-controller.h"
6 |
7 | #include "documents-model.h"
8 |
9 | using namespace CleanEditor::Models;
10 |
11 | namespace CleanEditor::Controllers {
12 |
13 | MainController::MainController(QObject *parent)
14 | : QObject{parent}
15 | {
16 | connect(&editor_controller_,
17 | &EditorController::textChanged,
18 | this,
19 | &MainController::handleEditorTextChanged);
20 | connect(&menu_controller_,
21 | &MenuController::saveFileClicked,
22 | this,
23 | &MainController::handleSaveFileClicked);
24 | connect(&menu_controller_,
25 | &MenuController::saveAsFileClicked,
26 | this,
27 | &MainController::handleSaveAsFileClicked);
28 | connect(&menu_controller_,
29 | &MenuController::newFileClicked,
30 | this,
31 | &MainController::handleNewFileClicked);
32 | connect(&menu_controller_,
33 | &MenuController::openFileClicked,
34 | this,
35 | &MainController::handleOpenFileClicked);
36 | connect(&file_navigation_controller_,
37 | &FileNavigationController::fileOpenedClicked,
38 | this,
39 | &MainController::handleOpenedFileClicked);
40 | }
41 |
42 | void MainController::setDocumentsModel(CleanEditor::Models::DocumentsModel &documents_model)
43 | {
44 | disconnect(document_created_connection_);
45 | documents_model_ = &documents_model;
46 | document_created_connection_ = connect(documents_model_,
47 | &DocumentsModel::documentCreated,
48 | this,
49 | &MainController::openDocument);
50 | }
51 |
52 | MenuController *MainController::menuController()
53 | {
54 | return &menu_controller_;
55 | }
56 |
57 | EditorController *MainController::editorController()
58 | {
59 | return &editor_controller_;
60 | }
61 |
62 | FileNavigationController *MainController::fileNavigationController()
63 | {
64 | return &file_navigation_controller_;
65 | }
66 |
67 | void MainController::handleEditorTextChanged()
68 | {
69 | if (!documents_model_) {
70 | return;
71 | }
72 |
73 | int current_file_id = editor_controller_.id();
74 | documents_model_->setNeedsUpdating(current_file_id);
75 | }
76 |
77 | void MainController::openDocument(const int id)
78 | {
79 | if (!documents_model_) {
80 | return;
81 | }
82 |
83 | editor_controller_.setText(documents_model_->fileContent(id));
84 | editor_controller_.setId(id);
85 |
86 | menu_controller_.setDocument(*documents_model_->document(id));
87 | file_navigation_controller_.setSelectedIndex(documents_model_->indexForId(id).row());
88 | }
89 |
90 | void MainController::handleSaveFileClicked()
91 | {
92 | if (!documents_model_) {
93 | return;
94 | }
95 |
96 | storeTextToCurrentFile();
97 | int current_file_id = editor_controller_.id();
98 | documents_model_->save(current_file_id);
99 | }
100 |
101 | void MainController::handleSaveAsFileClicked(const QUrl &url)
102 | {
103 | if (!documents_model_) {
104 | return;
105 | }
106 |
107 | storeTextToCurrentFile();
108 |
109 | int current_file_id = editor_controller_.id();
110 | documents_model_->saveAs(current_file_id, url);
111 | }
112 |
113 | void MainController::handleNewFileClicked()
114 | {
115 | if (!documents_model_) {
116 | return;
117 | }
118 |
119 | storeTextToCurrentFile();
120 | documents_model_->newFile();
121 | }
122 |
123 | void MainController::handleOpenedFileClicked(const int id)
124 | {
125 | if (!documents_model_) {
126 | return;
127 | }
128 |
129 | int current_file_id = editor_controller_.id();
130 | if (current_file_id == id) {
131 | return;
132 | }
133 |
134 | //First set the file content
135 | storeTextToCurrentFile();
136 | //Then open
137 | openDocument(id);
138 | }
139 |
140 | void MainController::handleOpenFileClicked(const QUrl &url)
141 | {
142 | storeTextToCurrentFile();
143 | documents_model_->openFile(url);
144 | }
145 |
146 | void MainController::storeTextToCurrentFile()
147 | {
148 | int current_file_id = editor_controller_.id();
149 | documents_model_->setFileContent(current_file_id, editor_controller_.text());
150 | }
151 |
152 | } // namespace CleanEditor::Controllers
153 |
--------------------------------------------------------------------------------
/lib/src/controllers/menu-controller.cpp:
--------------------------------------------------------------------------------
1 | #include "menu-controller.h"
2 | #include "menu-model.h"
3 |
4 | namespace CleanEditor::Controllers {
5 |
6 | MenuController::MenuController(QObject *parent)
7 | : QObject{parent}
8 | {}
9 |
10 | void MenuController::setModel(CleanEditor::Models::MenuModel &model)
11 | {
12 | model_ = &model;
13 | }
14 |
15 | void MenuController::setDocument(CleanEditor::Logic::DocumentHandler &document_handler)
16 | {
17 | if (!model_) {
18 | return;
19 | }
20 |
21 | model_->setDocument(document_handler);
22 | }
23 | } // namespace CleanEditor::Controllers
24 |
--------------------------------------------------------------------------------
/lib/src/document-handler.cpp:
--------------------------------------------------------------------------------
1 | #include "document-handler.h"
2 | #include "file-handler.h"
3 |
4 | namespace CleanEditor::Logic {
5 |
6 | static int next_id{1};
7 |
8 | DocumentHandler::DocumentHandler(QObject *parent)
9 | : QObject{parent}
10 | , id_{next_id++}
11 | {
12 | connect(&file_handler_, &FileHandler::fileUrlChanged, this, &DocumentHandler::fileUrlChanged);
13 | connect(&file_handler_, &FileHandler::error, this, &DocumentHandler::error);
14 | connect(&file_handler_, &FileHandler::fileOpened, this, &DocumentHandler::onFileOpened);
15 | }
16 |
17 | QString DocumentHandler::filename() const
18 | {
19 | return file_handler_.fileName();
20 | }
21 |
22 | QString DocumentHandler::fileType() const
23 | {
24 | return file_handler_.fileType();
25 | }
26 |
27 | QUrl DocumentHandler::fileUrl() const
28 | {
29 | return file_handler_.fileUrl();
30 | }
31 |
32 | QString DocumentHandler::textContent() const
33 | {
34 | return text_content_;
35 | }
36 |
37 | int DocumentHandler::id() const
38 | {
39 | return id_;
40 | }
41 |
42 | bool DocumentHandler::needsUpdating() const
43 | {
44 | return needs_updating_;
45 | }
46 |
47 | void DocumentHandler::setNeedsUpdating(const bool needs_updating)
48 | {
49 | if (needs_updating_ == needs_updating) {
50 | return;
51 | }
52 |
53 | if (needs_updating) {
54 | setNeedsSaving(true);
55 | }
56 |
57 | needs_updating_ = needs_updating;
58 | emit needsUpdatingChanged();
59 | }
60 |
61 | bool DocumentHandler::needsSaving() const
62 | {
63 | return needs_saving_;
64 | }
65 |
66 | bool DocumentHandler::isNewFile() const
67 | {
68 | return is_new_file_;
69 | }
70 |
71 | void DocumentHandler::load(const QUrl &file_url)
72 | {
73 | file_handler_.load(file_url);
74 | }
75 |
76 | void DocumentHandler::saveAs(const QUrl &file_url)
77 | {
78 | if (!file_handler_.saveAs(file_url, text_content_)) {
79 | return;
80 | }
81 | setIsNewFile(false);
82 | setNeedsSaving(false);
83 | setNeedsUpdating(false);
84 | }
85 |
86 | void DocumentHandler::save()
87 | {
88 | if (is_new_file_) {
89 | return;
90 | }
91 |
92 | if (!file_handler_.save(text_content_)) {
93 | return;
94 | }
95 | setNeedsSaving(false);
96 | setNeedsUpdating(false);
97 | }
98 |
99 | void DocumentHandler::setTextContent(const QString &text)
100 | {
101 | if (!needs_updating_) {
102 | return;
103 | }
104 | text_content_ = text;
105 | setNeedsUpdating(false);
106 | emit contentUpdated();
107 | }
108 |
109 | void DocumentHandler::setIsNewFile(const bool is_new_file)
110 | {
111 | if (is_new_file_ == is_new_file) {
112 | return;
113 | }
114 |
115 | is_new_file_ = is_new_file;
116 | emit isNewFileChanged();
117 | }
118 |
119 | void DocumentHandler::setNeedsSaving(bool needs_saving)
120 | {
121 | if (needs_saving_ == needs_saving) {
122 | return;
123 | }
124 |
125 | needs_saving_ = needs_saving;
126 | emit needsSavingChanged();
127 | }
128 |
129 | void DocumentHandler::onFileOpened()
130 | {
131 | needs_updating_ = true;
132 | setTextContent(file_handler_.data());
133 | needs_updating_ = false;
134 | setIsNewFile(false);
135 | emit fileOpened();
136 | }
137 |
138 | } //namespace CleanEditor::Logic
139 |
--------------------------------------------------------------------------------
/lib/src/file-handler.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #include "file-handler.h"
6 |
7 | namespace CleanEditor::Logic {
8 |
9 | FileHandler::FileHandler(QObject *parent)
10 | : QObject{parent}
11 | {}
12 |
13 | QString FileHandler::fileName() const
14 | {
15 | const auto file_path = localPathFromUrl(file_url_);
16 | const auto file_name = QFileInfo(file_path).fileName();
17 | if (file_name.isEmpty()) {
18 | return QStringLiteral("untitled");
19 | }
20 | return file_name;
21 | }
22 |
23 | QString FileHandler::fileType() const
24 | {
25 | return QFileInfo(fileName()).suffix();
26 | }
27 |
28 | QUrl FileHandler::fileUrl() const
29 | {
30 | return file_url_;
31 | }
32 |
33 | QString FileHandler::data() const
34 | {
35 | QFile file(localPathFromUrl(file_url_));
36 | if (!file.open(QFile::ReadOnly)) {
37 | return "";
38 | }
39 |
40 | return file.readAll();
41 | }
42 |
43 | void FileHandler::load(const QUrl &file_url)
44 | {
45 | if (file_url == file_url_) {
46 | return;
47 | }
48 |
49 | file_url_ = file_url;
50 | emit fileUrlChanged();
51 | const auto file_name = localPathFromUrl(file_url_);
52 | if (!QFile::exists(file_name)) {
53 | emit error(tr("File not found"));
54 | return;
55 | }
56 |
57 | QFile file(file_name);
58 | if (!file.open(QFile::ReadOnly)) {
59 | emit error(tr("Failed to open file"));
60 | }
61 |
62 | emit fileOpened();
63 | }
64 |
65 | bool FileHandler::saveAs(const QUrl &file_url, const QString &data)
66 | {
67 | const auto file_path = localPathFromUrl(file_url);
68 |
69 | QFile file(file_path);
70 | if (!file.open(QFile::WriteOnly | QFile::Truncate | QFile::Text)) {
71 | emit error(tr("Cannot save: ") + file.errorString());
72 | return false;
73 | }
74 |
75 | QTextStream stream{&file};
76 | stream << data;
77 |
78 | if (file_url == file_url_) {
79 | return true;
80 | }
81 |
82 | file_url_ = file_url;
83 | emit fileUrlChanged();
84 | return true;
85 | }
86 |
87 | bool FileHandler::save(const QString &data)
88 | {
89 | return saveAs(file_url_, data);
90 | }
91 |
92 | QString FileHandler::localPathFromUrl(const QUrl &file_url)
93 | {
94 | const auto path = file_url.toLocalFile();
95 | if (!path.isEmpty()) {
96 | return path;
97 | }
98 |
99 | return file_url.path();
100 | }
101 |
102 | } //namespace CleanEditor::Logic
103 |
--------------------------------------------------------------------------------
/lib/src/models/abstract-editor-model.cpp:
--------------------------------------------------------------------------------
1 | #include "abstract-editor-model.h"
2 |
3 | namespace CleanEditor::Models {
4 |
5 | AbstractEditorModel::AbstractEditorModel(QObject *parent)
6 | : QObject{parent}
7 | {}
8 |
9 | int AbstractEditorModel::id() const
10 | {
11 | return id_;
12 | }
13 |
14 | void AbstractEditorModel::setId(const int id)
15 | {
16 | if (id_ == id) {
17 | return;
18 | }
19 |
20 | id_ = id;
21 |
22 | emit idChanged();
23 | }
24 |
25 | } //namespace CleanEditor::Models
26 |
--------------------------------------------------------------------------------
/lib/src/models/documents-model.cpp:
--------------------------------------------------------------------------------
1 | #include "documents-model.h"
2 |
3 | using namespace CleanEditor::Logic;
4 |
5 | namespace CleanEditor::Models {
6 |
7 | DocumentsModel::DocumentsModel(QObject *parent)
8 | : QAbstractListModel{parent}
9 | {}
10 |
11 | int DocumentsModel::rowCount(const QModelIndex &parent) const
12 | {
13 | if (parent.isValid()) {
14 | return 0;
15 | }
16 |
17 | return static_cast(data_.size());
18 | }
19 |
20 | QVariant DocumentsModel::data(const QModelIndex &index, const int role) const
21 | {
22 | Q_ASSERT(checkIndex(index,
23 | QAbstractItemModel::CheckIndexOption::IndexIsValid
24 | | QAbstractItemModel::CheckIndexOption::ParentIsInvalid));
25 |
26 | const auto document = data_.at(static_cast(index.row())).get();
27 | QVariant data;
28 | switch (role) {
29 | case FileDocumentRole:
30 | data.setValue(document);
31 | break;
32 | case FileIdRole:
33 | data.setValue(document->id());
34 | break;
35 | case FilenameRole:
36 | case Qt::DisplayRole:
37 | data.setValue(document->filename());
38 | break;
39 | case FileTypeRole:
40 | data.setValue(document->fileType());
41 | break;
42 | case FileUrlRole:
43 | data.setValue(document->fileUrl());
44 | break;
45 | case FileContentRole:
46 | data.setValue(document->textContent());
47 | break;
48 | case FileNeedsUpdatingRole:
49 | data.setValue(document->needsUpdating());
50 | break;
51 | case FileNeedsSavingRole:
52 | data.setValue(document->needsSaving());
53 | break;
54 | case FileIsNewRole:
55 | data.setValue(document->isNewFile());
56 | break;
57 | default:
58 | return {};
59 | }
60 | return data;
61 | }
62 |
63 | QHash DocumentsModel::roleNames() const
64 | {
65 | QHash roles;
66 | roles[FileDocumentRole] = "fileDocumentRole";
67 | roles[FileIdRole] = "fileId";
68 | roles[FilenameRole] = "filename";
69 | roles[FileTypeRole] = "fileType";
70 | roles[FileUrlRole] = "fileUrl";
71 | roles[FileContentRole] = "fileContent";
72 | roles[FileNeedsUpdatingRole] = "fileNeedsUpdating";
73 | roles[FileNeedsSavingRole] = "fileNeedsSaving";
74 | return roles;
75 | }
76 |
77 | DocumentHandler *DocumentsModel::document(const int id) const
78 | {
79 | return getData(id, FileDocumentRole, nullptr);
80 | }
81 |
82 | QString DocumentsModel::filename(const int id) const
83 | {
84 | return getData(id, FilenameRole, QString{""});
85 | }
86 |
87 | QString DocumentsModel::fileType(const int id) const
88 | {
89 | return getData(id, FileTypeRole, QString{""});
90 | }
91 |
92 | QUrl DocumentsModel::fileUrl(const int id) const
93 | {
94 | return getData(id, FileUrlRole, QUrl{""});
95 | }
96 |
97 | bool DocumentsModel::isFileNew(const int id) const
98 | {
99 | return getData(id, FileIsNewRole, false);
100 | }
101 |
102 | bool DocumentsModel::needsUpdating(const int id) const
103 | {
104 | return getData(id, FileNeedsUpdatingRole, false);
105 | }
106 |
107 | bool DocumentsModel::needsSaving(const int id) const
108 | {
109 | return getData(id, FileNeedsSavingRole, false);
110 | }
111 |
112 | QString DocumentsModel::fileContent(const int id) const
113 | {
114 | return getData(id, FileContentRole, QString{""});
115 | }
116 |
117 | void DocumentsModel::setFileContent(const int id, const QString &text)
118 | {
119 | setData(id, &DocumentHandler::setTextContent, text);
120 | }
121 |
122 | void DocumentsModel::save(const int id)
123 | {
124 | setData(id, &DocumentHandler::save);
125 | }
126 |
127 | void DocumentsModel::saveAs(const int id, const QUrl &file_url)
128 | {
129 | setData(id, &DocumentHandler::saveAs, file_url);
130 | }
131 |
132 | void DocumentsModel::setNeedsUpdating(const int id)
133 | {
134 | setData(id, &DocumentHandler::setNeedsUpdating, true);
135 | }
136 |
137 | void DocumentsModel::newFile()
138 | {
139 | auto document_handler = std::make_unique();
140 | appendNewDocument(std::move(document_handler));
141 | }
142 |
143 | void DocumentsModel::openFile(const QUrl &file_url)
144 | {
145 | auto document_handler = std::make_unique();
146 | document_handler->load(file_url);
147 |
148 | appendNewDocument(std::move(document_handler));
149 | }
150 |
151 | void DocumentsModel::closeFile(const int id)
152 | {
153 | QModelIndex index = indexForId(id);
154 |
155 | if (!index.isValid()) {
156 | return;
157 | }
158 |
159 | const auto row_to_remove = static_cast(index.row());
160 | beginRemoveRows({}, row_to_remove, row_to_remove);
161 | data_.erase(data_.begin() + row_to_remove);
162 | endRemoveRows();
163 | }
164 |
165 | QModelIndex DocumentsModel::indexForId(const int id) const
166 | {
167 | size_t i{0};
168 | for (; i < data_.size(); i++) {
169 | if (data_.at(i)->id() == id) {
170 | break;
171 | }
172 | }
173 |
174 | //Not found
175 | if (i == data_.size()) {
176 | return QModelIndex{};
177 | }
178 |
179 | return index(static_cast(i), 0);
180 | }
181 |
182 | void DocumentsModel::appendNewDocument(std::unique_ptr document)
183 | {
184 | if (!document) {
185 | return;
186 | }
187 |
188 | const auto id = document->id();
189 | const auto index = static_cast(data_.size());
190 | beginInsertRows({}, index, index);
191 | data_.emplace_back(std::move(document));
192 | endInsertRows();
193 |
194 | emit documentCreated(id);
195 | }
196 |
197 | } //namespace CleanEditor::Models
198 |
--------------------------------------------------------------------------------
/lib/src/models/editor-model.cpp:
--------------------------------------------------------------------------------
1 | #include "editor-model.h"
2 |
3 | #include
4 | #include
5 |
6 | namespace CleanEditor::Models {
7 |
8 | EditorModel::EditorModel(QObject *parent)
9 | : AbstractEditorModel{parent}
10 | {}
11 |
12 | QString EditorModel::text() const
13 | {
14 | if (!text_document_) {
15 | return "";
16 | }
17 |
18 | return text_document_->toPlainText();
19 | }
20 |
21 | void EditorModel::setText(const QString &text)
22 | {
23 | if (!text_document_) {
24 | return;
25 | }
26 |
27 | { // Only block signals in scope
28 | QSignalBlocker block_signals{this};
29 | text_document_->setPlainText(text);
30 | }
31 |
32 | emit textReplaced();
33 | }
34 |
35 | void EditorModel::setTextDocument(QTextDocument *text_document)
36 | {
37 | text_document_ = text_document;
38 | if (!text_document_) {
39 | return;
40 | }
41 |
42 | connect(text_document_,
43 | &QTextDocument::contentsChanged,
44 | this,
45 | &AbstractEditorModel::textChanged);
46 | }
47 |
48 | } //namespace CleanEditor::Models
49 |
--------------------------------------------------------------------------------
/lib/src/models/file-navigation-model.cpp:
--------------------------------------------------------------------------------
1 | #include "file-navigation-model.h"
2 |
3 | namespace CleanEditor::Models {
4 |
5 | FileNavigationModel::FileNavigationModel(QObject *parent)
6 | : QObject{parent}
7 | {}
8 |
9 | int FileNavigationModel::selectedIndex() const
10 | {
11 | return selected_index_;
12 | }
13 |
14 | void FileNavigationModel::setSelectedIndex(const int index)
15 | {
16 | if (selected_index_ == index) {
17 | return;
18 | }
19 |
20 | selected_index_ = index;
21 | emit selectedIndexChanged();
22 | }
23 |
24 | } //namespace CleanEditor::Models
25 |
--------------------------------------------------------------------------------
/lib/src/models/menu-model.cpp:
--------------------------------------------------------------------------------
1 | #include "menu-model.h"
2 | #include "document-handler.h"
3 |
4 | using namespace CleanEditor::Logic;
5 |
6 | namespace CleanEditor::Models {
7 |
8 | MenuModel::MenuModel(QObject *parent)
9 | : QObject{parent}
10 | {}
11 |
12 | void MenuModel::setDocument(DocumentHandler &document_handler)
13 | {
14 | if (document_handler_ == &document_handler) {
15 | return;
16 | }
17 |
18 | if (document_handler_) {
19 | disconnect(document_handler_.data(),
20 | &DocumentHandler::fileUrlChanged,
21 | this,
22 | &MenuModel::titleChanged);
23 | disconnect(document_handler_.data(),
24 | &DocumentHandler::isNewFileChanged,
25 | this,
26 | &MenuModel::isNewFileChanged);
27 | }
28 |
29 | document_handler_ = &document_handler;
30 | if (!document_handler_) {
31 | return;
32 | }
33 |
34 | connect(document_handler_.data(),
35 | &DocumentHandler::fileUrlChanged,
36 | this,
37 | &MenuModel::titleChanged);
38 | connect(document_handler_.data(),
39 | &DocumentHandler::isNewFileChanged,
40 | this,
41 | &MenuModel::isNewFileChanged);
42 |
43 | emit titleChanged();
44 | emit isNewFileChanged();
45 | }
46 |
47 | QString MenuModel::title() const
48 | {
49 | if (!document_handler_) {
50 | return {};
51 | }
52 |
53 | return document_handler_->filename();
54 | }
55 |
56 | bool MenuModel::isNewFile() const
57 | {
58 | if (!document_handler_) {
59 | return false;
60 | }
61 | return document_handler_->isNewFile();
62 | }
63 |
64 | } //namespace CleanEditor::Models
65 |
--------------------------------------------------------------------------------
/lib/tests/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.8.2)
2 | cmake_policy(SET CMP0048 NEW)
3 | project(clean-editor-test VERSION 1.0.0 LANGUAGES C CXX)
4 |
5 | ###########################
6 | # Dependencies
7 |
8 | find_package(Qt6 COMPONENTS Test REQUIRED)
9 |
10 | ###########################
11 | # Targets
12 |
13 | add_executable(${PROJECT_NAME}
14 | # Tests
15 | src/file-handler-tests.h
16 | src/file-handler-tests.cpp
17 |
18 | src/document-handler-tests.h
19 | src/document-handler-tests.cpp
20 |
21 | src/documents-model-tests.h
22 | src/documents-model-tests.cpp
23 |
24 | # Necessary test runner classes
25 | src/test-runner.h
26 | src/test-runner.cpp
27 | src/main.cpp
28 | )
29 |
30 | target_include_directories(${PROJECT_NAME}
31 | PRIVATE
32 | src
33 | )
34 |
35 | target_link_libraries(${PROJECT_NAME}
36 | PRIVATE
37 | Qt6::Test
38 | clean-editor-lib
39 | )
40 |
41 | target_compile_features(${PROJECT_NAME}
42 | PRIVATE
43 | cxx_std_17
44 | )
45 |
46 | set_target_properties(${PROJECT_NAME}
47 | PROPERTIES
48 | AUTOMOC ON
49 | RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
50 | )
51 |
--------------------------------------------------------------------------------
/lib/tests/src/document-handler-tests.cpp:
--------------------------------------------------------------------------------
1 | #include "document-handler-tests.h"
2 | #include "document-handler.h"
3 |
4 | #include
5 | #include
6 | #include
7 |
8 | using namespace CleanEditor::Logic;
9 | static const constexpr char *kDummyContent = "dummy content in file";
10 |
11 | namespace CleanEditor::Tests {
12 |
13 | void DocumentHandlerTests::initTestCase()
14 | {
15 | if (tmp_file_.exists()) {
16 | return;
17 | }
18 | QVERIFY2(tmp_file_.open(), "Failed creating a temporary file");
19 | QFile file{tmp_file_.fileName()};
20 |
21 | QVERIFY(file.open(QIODevice::ReadWrite));
22 | QTextStream stream{&file};
23 |
24 | stream << kDummyContent;
25 | }
26 |
27 | void DocumentHandlerTests::checkInitialState_createEmptyFile_allPublicParameters()
28 | {
29 | DocumentHandler document;
30 |
31 | QVERIFY(document.isNewFile());
32 | QVERIFY(!document.needsUpdating());
33 | QVERIFY(!document.needsSaving());
34 | QCOMPARE(document.filename(), "untitled");
35 | QCOMPARE(document.fileType(), "");
36 | QVERIFY(document.fileUrl().isEmpty());
37 | QCOMPARE(document.textContent(), "");
38 | QVERIFY(document.id() > 0);
39 | }
40 |
41 | void DocumentHandlerTests::checkInitialState_openedFile_allPublicParameters()
42 | {
43 | DocumentHandler document;
44 |
45 | QSignalSpy document_opened_spy{&document, &DocumentHandler::fileOpened};
46 | QUrl file_url{tmp_file_.fileName()};
47 | document.load(file_url);
48 |
49 | QCOMPARE(document_opened_spy.count(), 1);
50 | QVERIFY(!document.isNewFile());
51 | QVERIFY(!document.needsUpdating());
52 | QVERIFY(!document.needsSaving());
53 | QCOMPARE(document.textContent(), QString{kDummyContent});
54 | QCOMPARE(document.fileUrl(), file_url);
55 | QCOMPARE(document.filename(), QFileInfo(tmp_file_.fileName()).fileName());
56 | QCOMPARE(document.fileType(), QFileInfo(tmp_file_.fileName()).suffix());
57 | QVERIFY(document.id() > 0);
58 | }
59 |
60 | void DocumentHandlerTests::save_newFile_stillNewFile()
61 | {
62 | DocumentHandler document;
63 | document.save();
64 | QVERIFY(document.isNewFile());
65 | }
66 |
67 | void DocumentHandlerTests::saveAs_newFile_noLongerNewFile()
68 | {
69 | DocumentHandler document;
70 |
71 | QSignalSpy file_url_changed{&document, &DocumentHandler::fileUrlChanged};
72 | QSignalSpy is_new_file_changed{&document, &DocumentHandler::isNewFileChanged};
73 | QUrl file_url{tmp_file_.fileName()};
74 | document.saveAs(file_url);
75 | QCOMPARE(file_url_changed.count(), 1);
76 | QCOMPARE(is_new_file_changed.count(), 1);
77 | QVERIFY(!document.isNewFile());
78 | QCOMPARE(document.fileUrl(), file_url);
79 | QCOMPARE(document.filename(), QFileInfo(tmp_file_.fileName()).fileName());
80 | QCOMPARE(document.fileType(), QFileInfo(tmp_file_.fileName()).suffix());
81 | }
82 |
83 | void DocumentHandlerTests::setContent_notNeedsUpdating_contentNotChanged()
84 | {
85 | DocumentHandler document;
86 |
87 | document.setNeedsUpdating(false); //same as default
88 | document.setTextContent("test");
89 | QVERIFY(document.textContent().isEmpty());
90 | }
91 |
92 | void DocumentHandlerTests::needsSaving_setNeedsUpdatingThenSave_needsSavingIsStillTrue()
93 | {
94 | DocumentHandler document;
95 | QVERIFY(!document.needsSaving());
96 | QSignalSpy needs_saving_changed{&document, &DocumentHandler::needsSavingChanged};
97 | document.setNeedsUpdating(true);
98 | QCOMPARE(needs_saving_changed.count(), 1);
99 | QVERIFY(document.needsSaving());
100 | document.save();
101 | QCOMPARE(needs_saving_changed.count(), 1);
102 | QVERIFY(document.needsSaving());
103 | }
104 |
105 | void DocumentHandlerTests::needsSaving_setNeedsUpdatingThenSaveAs_needsSavingIsNowFalse()
106 | {
107 | DocumentHandler document;
108 | QSignalSpy needs_saving_changed{&document, &DocumentHandler::needsSavingChanged};
109 | document.setNeedsUpdating(true);
110 | QCOMPARE(needs_saving_changed.count(), 1);
111 | QVERIFY(document.needsSaving());
112 | document.saveAs(QUrl{tmp_file_.fileName()});
113 | QCOMPARE(needs_saving_changed.count(), 2);
114 | QVERIFY(!document.needsSaving());
115 | QVERIFY(!document.needsUpdating());
116 | }
117 |
118 | void DocumentHandlerTests::textContent_updateTextContentAndSave_checkDifferentParams()
119 | {
120 | DocumentHandler document;
121 | document.setNeedsUpdating(true);
122 | document.setTextContent("test");
123 | QVERIFY(document.needsSaving());
124 | QVERIFY(!document.needsUpdating());
125 |
126 | document.saveAs(QUrl{tmp_file_.fileName()});
127 | QVERIFY(!document.needsSaving());
128 | QCOMPARE(document.textContent(), QString{"test"});
129 | }
130 |
131 | } //namespace CleanEditor::Tests
132 |
--------------------------------------------------------------------------------
/lib/tests/src/document-handler-tests.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 |
6 | #include "test-runner.h"
7 |
8 | namespace CleanEditor::Tests {
9 |
10 | class DocumentHandlerTests : public QObject
11 | {
12 | Q_OBJECT
13 |
14 | private slots:
15 | void initTestCase();
16 | void checkInitialState_createEmptyFile_allPublicParameters();
17 | void checkInitialState_openedFile_allPublicParameters();
18 | void save_newFile_stillNewFile();
19 | void saveAs_newFile_noLongerNewFile();
20 | void setContent_notNeedsUpdating_contentNotChanged();
21 | void needsSaving_setNeedsUpdatingThenSave_needsSavingIsStillTrue();
22 | void needsSaving_setNeedsUpdatingThenSaveAs_needsSavingIsNowFalse();
23 | void textContent_updateTextContentAndSave_checkDifferentParams();
24 |
25 | private:
26 | QTemporaryFile tmp_file_;
27 | };
28 |
29 | ADD_TEST_CLASS(DocumentHandlerTests);
30 |
31 | } //namespace CleanEditor::Tests
32 |
--------------------------------------------------------------------------------
/lib/tests/src/documents-model-tests.cpp:
--------------------------------------------------------------------------------
1 | #include "documents-model-tests.h"
2 |
3 | #include
4 | #include
5 | #include
6 | #include
7 |
8 | using namespace CleanEditor::Logic;
9 | using namespace CleanEditor::Models;
10 | static const constexpr char *kDummyContent = "dummy content in file";
11 |
12 | namespace CleanEditor::Tests {
13 |
14 | void DocumentsModelTests::initTestCase()
15 | {
16 | if (tmp_file_.exists()) {
17 | return;
18 | }
19 | QVERIFY2(tmp_file_.open(), "Failed creating a temporary file");
20 | QFile file{tmp_file_.fileName()};
21 |
22 | QVERIFY(file.open(QIODevice::ReadWrite));
23 | QTextStream stream{&file};
24 |
25 | stream << kDummyContent;
26 | }
27 |
28 | std::unique_ptr DocumentsModelTests::createEmptyModel()
29 | {
30 | auto documents_model = std::make_unique();
31 | new QAbstractItemModelTester{documents_model.get(),
32 | QAbstractItemModelTester::FailureReportingMode::QtTest,
33 | documents_model.get()};
34 | return documents_model;
35 | }
36 |
37 | void DocumentsModelTests::newFile_empty_newEmptyFileHasBeenCreated()
38 | {
39 | auto documents_model = createEmptyModel();
40 | QSignalSpy document_created{documents_model.get(), &DocumentsModel::documentCreated};
41 | documents_model->newFile();
42 |
43 | QCOMPARE(document_created.count(), 1);
44 | QCOMPARE(documents_model->rowCount(), 1);
45 |
46 | int id = document_created.first().first().toInt();
47 | QVERIFY(documents_model->isFileNew(id));
48 | QVERIFY(!documents_model->needsUpdating(id));
49 | QVERIFY(!documents_model->needsSaving(id));
50 | QCOMPARE(documents_model->filename(id), "untitled");
51 | QCOMPARE(documents_model->fileType(id), "");
52 | QVERIFY(documents_model->fileUrl(id).isEmpty());
53 | QCOMPARE(documents_model->fileContent(id), "");
54 | QVERIFY(documents_model->document(id) != nullptr);
55 | }
56 |
57 | void DocumentsModelTests::saveAs_newFile_openFileWithNewContent()
58 | {
59 | auto documents_model = createEmptyModel();
60 | QSignalSpy document_created{documents_model.get(), &DocumentsModel::documentCreated};
61 | documents_model->newFile();
62 | QCOMPARE(documents_model->rowCount(), 1);
63 |
64 | int id = document_created.first().first().toInt();
65 | documents_model->setNeedsUpdating(id);
66 | QVERIFY(documents_model->needsUpdating(id));
67 |
68 | documents_model->setFileContent(id, "new info");
69 | QVERIFY(!documents_model->needsUpdating(id));
70 | QCOMPARE(documents_model->fileContent(id), QString{"new info"});
71 |
72 | QUrl file_url{tmp_file_.fileName()};
73 | documents_model->saveAs(id, file_url);
74 |
75 | documents_model->openFile(file_url);
76 | QCOMPARE(documents_model->rowCount(), 2);
77 |
78 | int id2 = document_created.last().first().toInt();
79 | QVERIFY2(id != id2, "A new ID should have been generated when opening another document");
80 |
81 | QCOMPARE(documents_model->fileUrl(id2), file_url);
82 | QCOMPARE(documents_model->fileContent(id2), QString{"new info"});
83 | }
84 |
85 | } //namespace CleanEditor::Tests
86 |
--------------------------------------------------------------------------------
/lib/tests/src/documents-model-tests.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 | #include
6 |
7 | #include "documents-model.h"
8 | #include "test-runner.h"
9 |
10 | namespace CleanEditor::Tests {
11 |
12 | class DocumentsModelTests : public QObject
13 | {
14 | Q_OBJECT
15 |
16 | private slots:
17 | void initTestCase();
18 | void newFile_empty_newEmptyFileHasBeenCreated();
19 | void saveAs_newFile_openFileWithNewContent();
20 |
21 | private:
22 | QTemporaryFile tmp_file_;
23 | static std::unique_ptr createEmptyModel();
24 | };
25 |
26 | ADD_TEST_CLASS(DocumentsModelTests);
27 |
28 | } //namespace CleanEditor::Tests
29 |
--------------------------------------------------------------------------------
/lib/tests/src/file-handler-tests.cpp:
--------------------------------------------------------------------------------
1 | #include "file-handler-tests.h"
2 | #include "file-handler.h"
3 |
4 | #include
5 | #include
6 | #include
7 |
8 | using namespace CleanEditor::Logic;
9 | static const constexpr char *kDummyContent = "dummy content in file";
10 |
11 | namespace CleanEditor::Tests {
12 |
13 | void FileHandlerTests::initTestCase()
14 | {
15 | if (tmp_file_.exists()) {
16 | return;
17 | }
18 | QVERIFY2(tmp_file_.open(), "Failed creating a temporary file");
19 | QFile file{tmp_file_.fileName()};
20 |
21 | QVERIFY(file.open(QIODevice::ReadWrite));
22 | QTextStream stream{&file};
23 |
24 | stream << kDummyContent;
25 | }
26 |
27 | void FileHandlerTests::load_validFile_fileOpened()
28 | {
29 | FileHandler file_handler;
30 | QSignalSpy file_opened_spy(&file_handler, &FileHandler::fileOpened);
31 | file_handler.load(QUrl{tmp_file_.fileName()});
32 |
33 | QCOMPARE(file_opened_spy.count(), 1);
34 | }
35 |
36 | void FileHandlerTests::load_invalidFile_fileNotOpened()
37 | {
38 | FileHandler file_handler;
39 | QSignalSpy file_opened_spy(&file_handler, &FileHandler::fileOpened);
40 | file_handler.load(QUrl{"file_doesnt_exist"});
41 |
42 | QCOMPARE(file_opened_spy.count(), 0);
43 | }
44 |
45 | void FileHandlerTests::load_validFile_fileNameIsCorrect()
46 | {
47 | FileHandler file_handler;
48 | file_handler.load(QUrl{tmp_file_.fileName()});
49 | QCOMPARE(file_handler.fileName(), QFileInfo(tmp_file_.fileName()).fileName());
50 | }
51 |
52 | void FileHandlerTests::load_validFile_fileTypeIsCorrect()
53 | {
54 | FileHandler file_handler;
55 | file_handler.load(QUrl{tmp_file_.fileName()});
56 | QCOMPARE(file_handler.fileType(), QFileInfo(tmp_file_.fileName()).suffix());
57 | }
58 |
59 | void FileHandlerTests::load_validFile_fileUrlIsCorrect()
60 | {
61 | FileHandler file_handler;
62 | QUrl url{tmp_file_.fileName()};
63 | file_handler.load(url);
64 | QCOMPARE(file_handler.fileUrl(), url);
65 | }
66 |
67 | void FileHandlerTests::load_validFile_fileContentIsCorrect()
68 | {
69 | FileHandler file_handler;
70 | file_handler.load(QUrl{tmp_file_.fileName()});
71 | QCOMPARE(file_handler.data(), QString{kDummyContent});
72 | }
73 |
74 | void FileHandlerTests::load_validFile_noErrorsRecieved()
75 | {
76 | FileHandler file_handler;
77 | QSignalSpy error_spy(&file_handler, &FileHandler::error);
78 | file_handler.load(QUrl{tmp_file_.fileName()});
79 |
80 | QVERIFY(error_spy.count() == 0);
81 | }
82 |
83 | void FileHandlerTests::load_invalidFile_errorsRecieved()
84 | {
85 | FileHandler file_handler;
86 | QSignalSpy error_spy(&file_handler, &FileHandler::error);
87 | file_handler.load(QUrl{"file_doesnt_exist"});
88 |
89 | QVERIFY(error_spy.count() == 1);
90 | }
91 |
92 | void FileHandlerTests::save_emptyData_updatedData()
93 | {
94 | QTemporaryFile tmp_file;
95 | QVERIFY(tmp_file.open());
96 |
97 | FileHandler file_handler;
98 | file_handler.load(QUrl{tmp_file.fileName()});
99 | file_handler.save("new data saved");
100 |
101 | QCOMPARE(file_handler.data().toLocal8Bit().data(), "new data saved");
102 | }
103 |
104 | void FileHandlerTests::saveAs_emptyData_updatedData()
105 | {
106 | QTemporaryFile tmp_file;
107 | QVERIFY(tmp_file.open());
108 |
109 | FileHandler file_handler;
110 | file_handler.saveAs(QUrl{tmp_file.fileName()}, "new data saved");
111 |
112 | QFile file{tmp_file.fileName()};
113 | QVERIFY(file.open(QIODevice::ReadWrite));
114 |
115 | QTextStream stream{&file};
116 | QCOMPARE(stream.readAll().toLocal8Bit().data(), "new data saved");
117 | }
118 |
119 | } //namespace CleanEditor::Tests
120 |
--------------------------------------------------------------------------------
/lib/tests/src/file-handler-tests.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 |
6 | #include "test-runner.h"
7 |
8 | namespace CleanEditor::Tests {
9 |
10 | class FileHandlerTests : public QObject
11 | {
12 | Q_OBJECT
13 |
14 | private slots:
15 | void initTestCase();
16 | void load_validFile_fileOpened();
17 | void load_invalidFile_fileNotOpened();
18 | void load_validFile_fileNameIsCorrect();
19 | void load_validFile_fileTypeIsCorrect();
20 | void load_validFile_fileUrlIsCorrect();
21 | void load_validFile_fileContentIsCorrect();
22 | void load_validFile_noErrorsRecieved();
23 | void load_invalidFile_errorsRecieved();
24 | void save_emptyData_updatedData();
25 | void saveAs_emptyData_updatedData();
26 |
27 | private:
28 | QTemporaryFile tmp_file_;
29 | };
30 |
31 | ADD_TEST_CLASS(FileHandlerTests);
32 |
33 | } //namespace CleanEditor::Tests
34 |
--------------------------------------------------------------------------------
/lib/tests/src/main.cpp:
--------------------------------------------------------------------------------
1 | #include "test-runner.h"
2 |
3 | RUN_TESTS_MAIN
4 |
--------------------------------------------------------------------------------
/lib/tests/src/test-runner.cpp:
--------------------------------------------------------------------------------
1 | #include "test-runner.h"
2 |
3 | #include
4 | #include
5 |
6 | namespace CleanEditor::Util {
7 |
8 | TestRunner &TestRunner::instance()
9 | {
10 | static TestRunner runner;
11 | return runner;
12 | }
13 |
14 | int TestRunner::execTests(int argc, char **argv)
15 | {
16 | auto execTest = [argc, argv](QObject *test) { return QTest::qExec(test, argc, argv); };
17 |
18 | int status = 0;
19 | std::for_each(begin(tests_), end(tests_), [&status, &execTest](const auto &test) {
20 | status |= execTest(test);
21 | });
22 | return status;
23 | }
24 |
25 | } //namespace CleanEditor::Util
26 |
--------------------------------------------------------------------------------
/lib/tests/src/test-runner.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 | #include
6 |
7 | namespace CleanEditor::Util {
8 |
9 | class TestRunner
10 | {
11 | public:
12 | static TestRunner &instance();
13 |
14 | template
15 | T &addTest()
16 | {
17 | static T test;
18 | auto it = std::find(cbegin(tests_), cend(tests_), &test);
19 | if (it == cend(tests_)) {
20 | tests_.emplace_back(&test);
21 | }
22 | return test;
23 | }
24 | int execTests(int argc = 0, char **argv = nullptr);
25 |
26 | private:
27 | TestRunner() {}
28 | std::vector tests_;
29 | };
30 | } //namespace CleanEditor::Util
31 |
32 | #define ADD_TEST_CLASS(Class) \
33 | static Class &test_##Class = CleanEditor::Util::TestRunner::instance().addTest()
34 |
35 | #define RUN_TESTS_MAIN \
36 | int main(int argc, char **argv) \
37 | { \
38 | return CleanEditor::Util::TestRunner::instance().execTests(argc, argv); \
39 | }
40 |
--------------------------------------------------------------------------------
/screencapture.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Fagrell/clean-editor/0adc76100346191a577144b9d247d1db12c970ce/screencapture.png
--------------------------------------------------------------------------------
/ui-qml/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.8.2)
2 | cmake_policy(SET CMP0048 NEW)
3 | project(clean-editor-qml VERSION 1.0.0 LANGUAGES C CXX)
4 |
5 | ###########################
6 | # Dependencies
7 |
8 | find_package(Qt6 COMPONENTS Core Gui Qml Quick QuickControls2 REQUIRED)
9 |
10 | ###########################
11 | # Targets
12 |
13 | # Only used to make qml files accessible in VS
14 | file(GLOB_RECURSE QML_SRC "*.qml")
15 | source_group("Qml Files" FILES ${QML_SRC})
16 |
17 | add_executable(${PROJECT_NAME}
18 | src/main.cpp
19 | src/line-numbers.cpp
20 | src/line-numbers.h
21 | src/qml-editor-model.cpp
22 | src/qml-editor-model.h
23 | resources.qrc
24 | ${QML_SRC}
25 | )
26 |
27 | target_include_directories(${PROJECT_NAME}
28 | PUBLIC
29 | src
30 | )
31 |
32 | target_link_libraries(${PROJECT_NAME}
33 | PUBLIC
34 | Qt6::Core
35 | Qt6::Gui
36 | Qt6::Qml
37 | Qt6::Quick
38 | Qt6::QuickControls2
39 | clean-editor-lib
40 | )
41 |
42 | target_compile_features(${PROJECT_NAME}
43 | PUBLIC
44 | cxx_std_17
45 | )
46 |
47 | set_target_properties(${PROJECT_NAME}
48 | PROPERTIES
49 | AUTOMOC ON
50 | AUTORCC ON
51 | RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
52 | )
53 |
--------------------------------------------------------------------------------
/ui-qml/components/EditorComponent.qml:
--------------------------------------------------------------------------------
1 | import QtQuick 6.0
2 | import QtQuick.Controls 6.0
3 | import CleanEditor 1.0
4 | import "../styles"
5 |
6 | Item {
7 | id: root
8 | property alias text: textArea.text
9 |
10 | Rectangle {
11 | id: lineNumberPanel
12 | width: 50
13 | anchors {
14 | top: parent.top
15 | bottom: parent.bottom
16 | left: parent.left
17 | }
18 |
19 | color: Style.lineNumberBackground
20 |
21 | LineNumbers {
22 | id: lineNumbersItem
23 | anchors.fill: parent
24 | anchors.topMargin: 8
25 |
26 | selectedBackgroundColor: Style.lineNumberSelectedBackgroundColor
27 | currentBackgroundColor: Style.lineNumberCurrentBackgroundColor
28 | selectedTextColor: Style.lineNumberSelectedTextColor
29 | currentTextColor: Style.lineNumberCurrentTextColor
30 | textColor: Style.lineNumberTextColor
31 | font: Style.editorFont
32 |
33 | document: textArea.textDocument
34 | cursorPosition: textArea.cursorPosition
35 | selectionStart: textArea.selectionStart
36 | selectionEnd: textArea.selectionEnd
37 | offsetY: textEditor.contentY
38 | }
39 | }
40 |
41 | Flickable {
42 | id: textEditor
43 | anchors {
44 | top: parent.top
45 | bottom: parent.bottom
46 | right: parent.right
47 | left: lineNumberPanel.right
48 | leftMargin: 4
49 | }
50 | clip: true
51 | contentWidth: textArea.width
52 | contentHeight: textArea.height
53 | onContentYChanged: lineNumbersItem.update()
54 | boundsBehavior: Flickable.StopAtBounds
55 |
56 | TextArea.flickable: TextArea {
57 | id: textArea
58 | textFormat: Qt.PlainText
59 | background: null
60 | font: Style.editorFont
61 | selectByMouse: true
62 | onLinkActivated: Qt.openUrlExternally(link)
63 | selectionColor: Style.edtitorSelectionColor
64 |
65 | Component.onCompleted: {
66 | editorModel.document = textArea.textDocument
67 | }
68 | }
69 |
70 | ScrollBar.vertical: ScrollBar {}
71 | ScrollBar.horizontal: ScrollBar {}
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/ui-qml/components/FileNavigationComponent.qml:
--------------------------------------------------------------------------------
1 | import QtQuick 6.0
2 | import QtQuick.Controls 6.0
3 | import QtQuick.Controls.Material 6.0
4 | import CleanEditor 1.0
5 | import "../styles"
6 |
7 | Item {
8 | id: root
9 |
10 | Rectangle {
11 | id: openedFilesBar
12 | anchors.fill: parent
13 | color: Style.fileNavigationBackgroundColor
14 |
15 | ButtonGroup {
16 | id: openedFileButtonGroup
17 | }
18 |
19 | Component {
20 | id: openedFilesDelegate
21 |
22 | Item {
23 | width: openedFilesBar.width
24 | height: 25
25 |
26 | Button {
27 | id: button
28 | checked: (index === listView.currentIndex) ? true : false
29 | checkable: true
30 | anchors.fill: parent
31 | text: filename + (fileNeedsSaving ? "*" : "")
32 | ButtonGroup.group: openedFileButtonGroup
33 | onClicked: mainController.fileNavigationController.fileOpenedClicked(fileId)
34 | background: Rectangle {
35 | color: {
36 | if (button.checked) {
37 | return Style.fileNavigationSelectedColor
38 | }
39 | if (button.hovered) {
40 | return Style.fileNavigationHoveredColor
41 | }
42 |
43 | return Style.fileNavigationBackgroundColor
44 | }
45 | border.width: 0
46 | radius: 0
47 | }
48 | contentItem: Text {
49 | text: button.text
50 | verticalAlignment: Text.AlignVCenter
51 | color: Style.fileNavigationTextColor
52 | }
53 | }
54 | }
55 | }
56 |
57 | ScrollView {
58 | id: scrollView
59 | anchors.fill: parent
60 |
61 | ListView {
62 | id: listView
63 | anchors.fill: parent
64 | model: documentsModel
65 | delegate: openedFilesDelegate
66 | focus: true
67 | highlightFollowsCurrentItem: true
68 | currentIndex: fileNavigationModel.selectedIndex
69 | }
70 | }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/ui-qml/components/MenuComponent.qml:
--------------------------------------------------------------------------------
1 | import QtQuick 6.0
2 | import QtQuick.Layouts 6.0
3 | import QtQuick.Controls 6.0
4 | import QtQuick.Controls.Material 6.0
5 | import Qt.labs.platform 1.1
6 | import "../styles"
7 |
8 | ToolBar {
9 |
10 | property alias title: menuTitle.text
11 |
12 | leftPadding: 8
13 | Material.elevation: 4
14 |
15 | RowLayout {
16 | id: fileRow
17 | anchors.fill: parent
18 | MenuToolButton {
19 | id: newButton
20 | text: "\uE800" // icon-doc-text-inv-1
21 | focusPolicy: Qt.TabFocus
22 | onClicked: mainController.menuController.newFileClicked();
23 | }
24 |
25 | MenuToolButton {
26 | id: openButton
27 | text: "\uE802" // icon-folder
28 | focusPolicy: Qt.TabFocus
29 | onClicked: openDialog.open()
30 | }
31 | MenuToolButton {
32 | id: saveButton
33 | text: "\uE801" // icon-floppy
34 | focusPolicy: Qt.TabFocus
35 | onClicked: saveDialog.open()
36 | }
37 | Text {
38 | id: menuTitle
39 | text: menuModel.title
40 | horizontalAlignment: Qt.AlignHCenter
41 | verticalAlignment: Qt.AlignVCenter
42 | Layout.fillWidth: true
43 | color: Style.menuTitleColor
44 | font: Style.menuTitleFont
45 | }
46 | }
47 |
48 | FileDialog {
49 | id: openDialog
50 | fileMode: FileDialog.OpenFile
51 | selectedNameFilter.index: 1
52 | nameFilters: ["*"]
53 | folder: StandardPaths.writableLocation(StandardPaths.DocumentsLocation)
54 | onAccepted: mainController.menuController.openFileClicked(file)
55 | }
56 |
57 | FileDialog {
58 | id: saveDialog
59 | fileMode: FileDialog.SaveFile
60 | nameFilters: openDialog.nameFilters
61 | folder: StandardPaths.writableLocation(StandardPaths.DocumentsLocation)
62 | onAccepted: mainController.menuController.saveAsFileClicked(file);
63 | }
64 |
65 | Shortcut {
66 | id: openShortcut
67 | sequence: StandardKey.Open
68 | onActivated: openDialog.open()
69 | }
70 |
71 | Shortcut {
72 | id: saveAsShortcut
73 | sequence: StandardKey.SaveAs
74 | onActivated: saveDialog.open()
75 | }
76 |
77 | Shortcut {
78 | id: saveShortcut
79 | sequence: StandardKey.Save
80 | onActivated: menuModel.isNewFile ? saveDialog.open() : mainController.menuController.saveFileClicked();
81 | }
82 |
83 | Shortcut {
84 | id: newShortcut
85 | sequence: StandardKey.New
86 | onActivated: mainController.menuController.newFileClicked();
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/ui-qml/components/qmldir:
--------------------------------------------------------------------------------
1 | module components
2 | EditorComponent 1.0 EditorComponent.qml
3 | FileNavigationComponent 1.0 FileNavigationComponent.qml
4 | MenuComponent 1.0 MenuComponent.qml
5 |
--------------------------------------------------------------------------------
/ui-qml/fonts/Hack-Bold.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Fagrell/clean-editor/0adc76100346191a577144b9d247d1db12c970ce/ui-qml/fonts/Hack-Bold.ttf
--------------------------------------------------------------------------------
/ui-qml/fonts/Hack-BoldItalic.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Fagrell/clean-editor/0adc76100346191a577144b9d247d1db12c970ce/ui-qml/fonts/Hack-BoldItalic.ttf
--------------------------------------------------------------------------------
/ui-qml/fonts/Hack-Italic.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Fagrell/clean-editor/0adc76100346191a577144b9d247d1db12c970ce/ui-qml/fonts/Hack-Italic.ttf
--------------------------------------------------------------------------------
/ui-qml/fonts/Hack-Regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Fagrell/clean-editor/0adc76100346191a577144b9d247d1db12c970ce/ui-qml/fonts/Hack-Regular.ttf
--------------------------------------------------------------------------------
/ui-qml/fonts/fontello.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Fagrell/clean-editor/0adc76100346191a577144b9d247d1db12c970ce/ui-qml/fonts/fontello.ttf
--------------------------------------------------------------------------------
/ui-qml/qtquickcontrols2.conf:
--------------------------------------------------------------------------------
1 | [Controls]
2 | Style=Material
3 |
4 | [Material]
5 | Primary=#D3D3D3
6 | Foreground=#444444
7 | Accent=#D3D3D3
8 | Theme=System
9 |
10 | [Universal]
11 | Theme=System
12 |
13 | [Default]
14 | Font\Family=Open Sans
15 | Font\PixelSize=20
16 |
17 | [Material\Font]
18 | Family=Open Sans
19 | PixelSize=20
20 |
--------------------------------------------------------------------------------
/ui-qml/resources.qrc:
--------------------------------------------------------------------------------
1 |
2 |
3 | qtquickcontrols2.conf
4 |
5 |
6 | views/MainView.qml
7 |
8 |
9 | components/EditorComponent.qml
10 | components/FileNavigationComponent.qml
11 | components/MenuComponent.qml
12 |
13 |
14 | fonts/fontello.ttf
15 | fonts/Hack-Regular.ttf
16 | fonts/Hack-Bold.ttf
17 | fonts/Hack-BoldItalic.ttf
18 | fonts/Hack-Italic.ttf
19 |
20 |
21 | styles/Style.qml
22 | styles/qmldir
23 | styles/MenuToolButton.qml
24 |
25 |
26 |
--------------------------------------------------------------------------------
/ui-qml/src/line-numbers.cpp:
--------------------------------------------------------------------------------
1 | #include "line-numbers.h"
2 |
3 | #include
4 | #include
5 | #include
6 | #include
7 |
8 | #include
9 | #include
10 |
11 | namespace CleanEditor::UI {
12 |
13 | static constexpr int kLineNumberXOffset{5};
14 |
15 | LineNumbers::LineNumbers(QQuickPaintedItem *parent)
16 | : QQuickPaintedItem(parent)
17 | {
18 | font_.setStyleHint(QFont::TypeWriter);
19 | }
20 |
21 | QQuickTextDocument *LineNumbers::document() const
22 | {
23 | return document_.data();
24 | }
25 |
26 | void LineNumbers::setFont(const QFont &font)
27 | {
28 | if (font_ == font) {
29 | return;
30 | }
31 |
32 | font_ = font;
33 | line_height_ = QFontMetrics{font}.height();
34 | update();
35 | }
36 |
37 | void LineNumbers::setSelectedBackgroundColor(const QColor &color)
38 | {
39 | if (selected_background_color_ == color) {
40 | return;
41 | }
42 |
43 | selected_background_color_ = color;
44 | update();
45 | }
46 |
47 | void LineNumbers::setCurrentBackgroundColor(const QColor &color)
48 | {
49 | if (current_background_color_ == color) {
50 | return;
51 | }
52 |
53 | current_background_color_ = color;
54 | update();
55 | }
56 |
57 | void LineNumbers::setSelectedTextColor(const QColor &color)
58 | {
59 | if (selected_text_color_ == color) {
60 | return;
61 | }
62 |
63 | selected_text_color_ = color;
64 | update();
65 | }
66 |
67 | void LineNumbers::setCurrentTextColor(const QColor &color)
68 | {
69 | if (current_text_color_ == color) {
70 | return;
71 | }
72 |
73 | current_text_color_ = color;
74 | update();
75 | }
76 |
77 | void LineNumbers::setTextColor(const QColor &color)
78 | {
79 | if (text_color_ == color) {
80 | return;
81 | }
82 |
83 | text_color_ = color;
84 | update();
85 | }
86 |
87 | void LineNumbers::setDocument(QQuickTextDocument *document)
88 | {
89 | if (document_ == document) {
90 | return;
91 | }
92 |
93 | document_ = document;
94 | if (!document_) {
95 | return;
96 | }
97 |
98 | auto text_document = document_->textDocument();
99 | connect(text_document, &QTextDocument::contentsChanged, this, [this]() { update(); });
100 | update();
101 | }
102 |
103 | void LineNumbers::setOffsetY(const int offset_y)
104 | {
105 | if (offset_y_ == offset_y) {
106 | return;
107 | }
108 |
109 | offset_y_ = offset_y;
110 | update();
111 | }
112 |
113 | void LineNumbers::setCursorPosition(const int cursor_position)
114 | {
115 | if (cursor_position_ == cursor_position) {
116 | return;
117 | }
118 |
119 | cursor_position_ = cursor_position;
120 | line_cursor_position_ = positionToLine(cursor_position);
121 | update();
122 | }
123 |
124 | void LineNumbers::setSelectionStart(const int selection_start)
125 | {
126 | if (selection_start_ == selection_start) {
127 | return;
128 | }
129 |
130 | selection_start_ = selection_start;
131 | line_selection_start_ = positionToLine(selection_start);
132 | update();
133 | }
134 |
135 | void LineNumbers::setSelectionEnd(const int selection_end)
136 | {
137 | if (selection_end_ == selection_end) {
138 | return;
139 | }
140 |
141 | selection_end_ = selection_end;
142 | line_selection_end_ = positionToLine(selection_end);
143 | update();
144 | }
145 |
146 | int LineNumbers::positionToLine(const int position) const
147 | {
148 | if (!document_) {
149 | return -1;
150 | }
151 |
152 | auto text_document = document_->textDocument();
153 | return countLines(text_document->toPlainText().first(position));
154 | }
155 |
156 | void LineNumbers::paint(QPainter *painter)
157 | {
158 | int first_visible_line = firstVisibleLine();
159 | int additional_offset = offset_y_ % static_cast(line_height_);
160 | QColor text_color;
161 | int visible_lines = numberOfVisibleLines();
162 |
163 | for (int i{0}; i < visible_lines; i++) {
164 | int line_number = i + first_visible_line;
165 | qreal line_y_position = i * line_height_ - additional_offset;
166 |
167 | if (isCurrentLine(line_number)) {
168 | drawLineBackground(*painter, line_y_position, current_background_color_);
169 | text_color = current_text_color_;
170 | } else if (isLineSelected(line_number)) {
171 | drawLineBackground(*painter, line_y_position, selected_background_color_);
172 | text_color = selected_text_color_;
173 | } else {
174 | text_color = text_color_;
175 | }
176 |
177 | drawLineNumber(*painter, line_y_position, text_color, line_number);
178 | }
179 | }
180 |
181 | int LineNumbers::firstVisibleLine() const
182 | {
183 | return offset_y_ / static_cast(line_height_) + 1;
184 | }
185 |
186 | int LineNumbers::numberOfVisibleLines() const
187 | {
188 | auto first_visible_line = firstVisibleLine();
189 | auto possible_visible_lines = static_cast(height() / line_height_);
190 |
191 | // Check if we've reached the bottom of the page
192 | int possible_page_count = std::min(first_visible_line + possible_visible_lines, lineCount());
193 |
194 | return possible_page_count - first_visible_line + 1;
195 | }
196 |
197 | int LineNumbers::lineCount() const
198 | {
199 | if (!document_) {
200 | return 0;
201 | }
202 |
203 | auto text_document = document_->textDocument();
204 | return countLines(text_document->toPlainText());
205 | }
206 |
207 | bool LineNumbers::isLineSelected(const int line) const
208 | {
209 | return (line >= line_selection_start_) && (line <= line_selection_end_);
210 | }
211 |
212 | bool LineNumbers::isCurrentLine(const int line) const
213 | {
214 | return line == line_cursor_position_;
215 | }
216 |
217 | void LineNumbers::drawLineBackground(QPainter &painter,
218 | const qreal y_position,
219 | const QColor &background_color)
220 | {
221 | QRectF background_rectangle(0, y_position, width(), line_height_);
222 | painter.setPen(QPen{background_color});
223 | painter.drawRect(background_rectangle);
224 | painter.fillRect(background_rectangle, background_color);
225 | }
226 |
227 | void LineNumbers::drawLineNumber(QPainter &painter,
228 | const qreal y_position,
229 | const QColor &text_color,
230 | const int line_number)
231 | {
232 | painter.setFont(font_);
233 | painter.setPen(QPen{text_color});
234 | QRectF text_bounding_rectangle{0, y_position, width() - kLineNumberXOffset, line_height_};
235 | painter.drawText(text_bounding_rectangle, Qt::AlignRight, QString::number(line_number));
236 | }
237 |
238 | int LineNumbers::countLines(QStringView text)
239 | {
240 | int lines = 1;
241 | lines += std::count_if(std::begin(text), std::end(text), [](const auto &symbol) {
242 | return (symbol == '\n' || symbol == '\r');
243 | });
244 | return lines;
245 | }
246 |
247 | } // namespace CleanEditor::UI
248 |
--------------------------------------------------------------------------------
/ui-qml/src/line-numbers.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 |
10 | namespace CleanEditor::UI {
11 |
12 | /*!
13 | * \brief The LineNumbers class paints line numbers (vertically) in an item.
14 | * It's possible to define the text color and the background for the currently selected line, see currentTextColor
15 | * and currentBackgroundColor.
16 | *
17 | * It's also possible to define the text color and the background for lines that have been selected across multiple rows,
18 | * see selectedTextColor and selectedBackgroundColor.
19 | *
20 | * textColor is the color used by the lines that are not selected.
21 | *
22 | * Internally uses the QTextDocument to identify selected lines.
23 | *
24 | * offsetY is used to know if we've scrolled in the document. Top of the page means offsetY == 0.
25 | *
26 | */
27 | class LineNumbers : public QQuickPaintedItem
28 | {
29 | Q_OBJECT
30 | Q_DISABLE_COPY_MOVE(LineNumbers)
31 |
32 | Q_PROPERTY(QFont font MEMBER font_ WRITE setFont)
33 | Q_PROPERTY(QColor selectedBackgroundColor MEMBER selected_background_color_ WRITE
34 | setSelectedBackgroundColor)
35 | Q_PROPERTY(QColor currentBackgroundColor MEMBER current_background_color_ WRITE
36 | setCurrentBackgroundColor)
37 | Q_PROPERTY(QColor selectedTextColor MEMBER selected_text_color_ WRITE setSelectedTextColor)
38 | Q_PROPERTY(QColor currentTextColor MEMBER current_text_color_ WRITE setCurrentTextColor)
39 | Q_PROPERTY(QColor textColor MEMBER text_color_ WRITE setTextColor)
40 |
41 | Q_PROPERTY(QQuickTextDocument *document READ document WRITE setDocument)
42 | Q_PROPERTY(int offsetY MEMBER offset_y_ WRITE setOffsetY)
43 | Q_PROPERTY(int cursorPosition MEMBER cursor_position_ WRITE setCursorPosition)
44 | Q_PROPERTY(int selectionStart MEMBER selection_start_ WRITE setSelectionStart)
45 | Q_PROPERTY(int selectionEnd MEMBER selection_end_ WRITE setSelectionEnd)
46 |
47 | public:
48 | explicit LineNumbers(QQuickPaintedItem *parent = nullptr);
49 |
50 | QQuickTextDocument *document() const;
51 |
52 | public Q_SLOTS:
53 | //! Set the font (and internally also sets the line height)
54 | void setFont(const QFont &font);
55 | void setSelectedBackgroundColor(const QColor &color);
56 | void setCurrentBackgroundColor(const QColor &color);
57 | void setSelectedTextColor(const QColor &color);
58 | void setCurrentTextColor(const QColor &color);
59 | void setTextColor(const QColor &color);
60 |
61 | void setDocument(QQuickTextDocument *document);
62 | void setOffsetY(int offset_y);
63 | void setCursorPosition(int cursor_position);
64 | void setSelectionStart(int selection_start);
65 | void setSelectionEnd(int selection_end);
66 |
67 | protected:
68 | void paint(QPainter *painter) override;
69 |
70 | private:
71 | int line_count_{0};
72 | int offset_y_{0};
73 | qreal line_height_{0};
74 |
75 | int cursor_position_{-1};
76 | int selection_start_{-1};
77 | int selection_end_{-1};
78 |
79 | int line_cursor_position_{0};
80 | int line_selection_start_{0};
81 | int line_selection_end_{0};
82 |
83 | QPointer document_;
84 | QFont font_{"Monospace", 12};
85 | QColor selected_background_color_{Qt::lightGray};
86 | QColor current_background_color_{Qt::darkGray};
87 | QColor selected_text_color_{Qt::darkGray};
88 | QColor current_text_color_{Qt::white};
89 | QColor text_color_{Qt::darkGray};
90 |
91 | int positionToLine(int position) const;
92 | int firstVisibleLine() const;
93 | int numberOfVisibleLines() const;
94 | int lineCount() const;
95 | bool isLineSelected(int line) const;
96 | bool isCurrentLine(int line) const;
97 |
98 | void drawLineBackground(QPainter &painter, qreal y_position, const QColor &background_color);
99 | void drawLineNumber(QPainter &painter,
100 | qreal y_position,
101 | const QColor &text_color,
102 | int line_number);
103 |
104 | static int countLines(QStringView text);
105 | };
106 |
107 | } // namespace CleanEditor::UI
108 |
--------------------------------------------------------------------------------
/ui-qml/src/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 |
6 | #include "editor-controller.h"
7 | #include "file-navigation-controller.h"
8 | #include "main-controller.h"
9 | #include "menu-controller.h"
10 |
11 | #include "document-handler.h"
12 | #include "documents-model.h"
13 | #include "file-navigation-model.h"
14 | #include "line-numbers.h"
15 | #include "menu-model.h"
16 | #include "qml-editor-model.h"
17 |
18 | using namespace CleanEditor::Controllers;
19 | using namespace CleanEditor::Logic;
20 | using namespace CleanEditor::Models;
21 | using namespace CleanEditor::UI;
22 |
23 | int main(int argc, char *argv[])
24 | {
25 | QGuiApplication::setApplicationName("Clean Editor");
26 | QGuiApplication::setOrganizationName("cleanqt.io");
27 |
28 | QGuiApplication app(argc, argv);
29 |
30 | const auto addFonts = [](const auto &... fonts) {
31 | const auto addFont = [](const auto &font) {
32 | if (QFontDatabase::addApplicationFont(font) == -1) {
33 | qWarning() << "Failed to load font: " << font;
34 | }
35 | };
36 | (addFont(fonts), ...);
37 | };
38 |
39 | addFonts(":/fonts/Hack-Regular.ttf",
40 | ":/fonts/Hack-Bold.ttf",
41 | ":/fonts/Hack-BoldItalic.ttf",
42 | ":/fonts/Hack-Italic.ttf",
43 | ":/fonts/fontello.ttf");
44 |
45 | qmlRegisterType("CleanEditor", 1, 0, "MainController");
46 | qmlRegisterType("CleanEditor", 1, 0, "MenuController");
47 | qmlRegisterType("CleanEditor", 1, 0, "FileNavigationController");
48 | qmlRegisterType("CleanEditor", 1, 0, "DocumentHandler");
49 | qmlRegisterType("CleanEditor", 1, 0, "LineNumbers");
50 |
51 | MainController main_controller;
52 | DocumentsModel documents_model;
53 | main_controller.setDocumentsModel(documents_model);
54 |
55 | QmlEditorModel editor_model;
56 | main_controller.editorController()->setModel(editor_model);
57 |
58 | MenuModel menu_model;
59 | main_controller.menuController()->setModel(menu_model);
60 |
61 | FileNavigationModel file_navigation_model;
62 | main_controller.fileNavigationController()->setModel(file_navigation_model);
63 |
64 | main_controller.menuController()->newFileClicked(); //Create a new file to start with!
65 |
66 | QQmlApplicationEngine engine;
67 | engine.rootContext()->setContextProperty("mainController", &main_controller);
68 | engine.rootContext()->setContextProperty("documentsModel", &documents_model);
69 | engine.rootContext()->setContextProperty("editorModel", &editor_model);
70 | engine.rootContext()->setContextProperty("menuModel", &menu_model);
71 | engine.rootContext()->setContextProperty("fileNavigationModel", &file_navigation_model);
72 | engine.load(QUrl(QStringLiteral("qrc:/views/MainView.qml")));
73 |
74 | if (engine.rootObjects().isEmpty()) {
75 | return -1;
76 | }
77 |
78 | return app.exec();
79 | }
80 |
--------------------------------------------------------------------------------
/ui-qml/src/qml-editor-model.cpp:
--------------------------------------------------------------------------------
1 | #include "qml-editor-model.h"
2 |
3 | #include
4 |
5 | namespace CleanEditor::Models {
6 |
7 | QmlEditorModel::QmlEditorModel(QObject *parent)
8 | : EditorModel{parent}
9 | {}
10 |
11 | QQuickTextDocument *QmlEditorModel::document() const
12 | {
13 | return document_;
14 | }
15 |
16 | void QmlEditorModel::setDocument(QQuickTextDocument *document)
17 | {
18 | setTextDocument(nullptr);
19 | document_ = document;
20 |
21 | if (!document_) {
22 | return;
23 | }
24 |
25 | setTextDocument(document_->textDocument());
26 | }
27 |
28 | } //namespace CleanEditor::Models
29 |
--------------------------------------------------------------------------------
/ui-qml/src/qml-editor-model.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "editor-model.h"
4 | class QQuickTextDocument;
5 |
6 | namespace CleanEditor::Models {
7 |
8 | /*!
9 | * \brief The QmlEditorModel class is used to expose the EditorModel to an
10 | * Qml-component that's using a QQuickTextDocument internally.
11 | * See EditorModel for more information.
12 | *
13 | * \sa EditorModel
14 | */
15 | class QmlEditorModel : public EditorModel
16 | {
17 | Q_OBJECT
18 | Q_DISABLE_COPY_MOVE(QmlEditorModel)
19 |
20 | Q_PROPERTY(QQuickTextDocument *document READ document WRITE setDocument NOTIFY documentChanged)
21 |
22 | public:
23 | explicit QmlEditorModel(QObject *parent = nullptr);
24 |
25 | QQuickTextDocument *document() const;
26 | void setDocument(QQuickTextDocument *document);
27 |
28 | Q_SIGNALS:
29 | void documentChanged();
30 |
31 | private:
32 | QTextDocument *textDocument() const;
33 |
34 | QQuickTextDocument *document_{nullptr};
35 | };
36 |
37 | } //namespace CleanEditor::Models
38 |
--------------------------------------------------------------------------------
/ui-qml/styles/MenuToolButton.qml:
--------------------------------------------------------------------------------
1 | import QtQuick 6.0
2 | import QtQuick.Controls 6.0
3 | import "."
4 |
5 | ToolButton {
6 | id: root
7 | contentItem: Text {
8 | text: root.text
9 | font.family: "fontello"
10 | font.pointSize: Style.menuIconSize
11 | horizontalAlignment: Text.AlignHCenter
12 | verticalAlignment: Text.AlignVCenter
13 | color: Style.menuIconColor
14 | }
15 | }
16 |
17 |
18 |
--------------------------------------------------------------------------------
/ui-qml/styles/Style.qml:
--------------------------------------------------------------------------------
1 | pragma Singleton
2 | import QtQuick 6.0
3 |
4 | QtObject {
5 | id: style
6 |
7 | //General used by many properties
8 | property color mainBlueColor: "#161161"
9 |
10 | //LineNumbers properties
11 | property color lineNumberBackground: "#d3d3d3"
12 | property color lineNumberSelectedBackgroundColor: "#b2d7ff"
13 | property alias lineNumberCurrentBackgroundColor: style.mainBlueColor
14 | property alias lineNumberSelectedTextColor: style.mainBlueColor
15 | property color lineNumberCurrentTextColor: "white"
16 | property alias lineNumberTextColor: style.mainBlueColor
17 |
18 | //Editor properties
19 | property font editorFont: Qt.font({family: "Hack", pointSize: 12})
20 | property alias edtitorSelectionColor: style.lineNumberSelectedBackgroundColor
21 |
22 | //Menu properties
23 | property int menuIconSize: 14
24 | property alias menuIconColor: style.mainBlueColor
25 | property alias menuTitleColor: style.mainBlueColor
26 | property font menuTitleFont: Qt.font({bold: true, pointSize: 16})
27 |
28 | //FileNavigation properties
29 | property alias fileNavigationBackgroundColor: style.mainBlueColor
30 | property color fileNavigationSelectedColor: "#223D6B"
31 | property color fileNavigationHoveredColor: "#1d195e"
32 | property color fileNavigationTextColor: "white"
33 | }
34 |
--------------------------------------------------------------------------------
/ui-qml/styles/qmldir:
--------------------------------------------------------------------------------
1 | singleton Style 1.0 Style.qml
2 |
--------------------------------------------------------------------------------
/ui-qml/views/MainView.qml:
--------------------------------------------------------------------------------
1 | import QtQuick 6.0
2 | import QtQuick.Window 6.0
3 | import QtQuick.Controls 6.0
4 | import QtQml 6.0
5 | import CleanEditor 1.0
6 | import "../components"
7 |
8 | ApplicationWindow {
9 | id: root
10 |
11 | visible: true
12 | width: 640
13 | height: 480
14 | title: qsTr("Clean Editor")
15 |
16 | header: MenuComponent {
17 | id: menu
18 | width: parent.width
19 | }
20 |
21 | FileNavigationComponent {
22 | id: fileNavigation
23 | anchors {
24 | top: parent.top
25 | left: parent.left
26 | bottom: parent.bottom
27 | }
28 | width: 200
29 | }
30 |
31 | EditorComponent {
32 | id: editor
33 | anchors {
34 | top: parent.top
35 | bottom: parent.bottom
36 | right: parent.right
37 | left: fileNavigation.right
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------