The problem at the moment is that the two left buttons are not part
of the scrollable area on the right, and the scrollable area has been
manually positioned. We would need to move the buttons into the toolbar
area, and then hide them when using the desktop editor. For now, I've
just added wrapping/smaller text instead.
https://forums.ankiweb.net/t/image-occlusion-editor-buttons-overlap-in-some-languages/38499
- We were registered another event handler for each card, which was a
resource leak, and would lead to the shortcut failing on every second card
due to the even number of toggles.
- We were allowing toggleMasks() to run even when the button wasn't visible
(e.g., when showing the question side of a card)
* remove unfinished polygon and remove selectable for shapes in polygon mode
* make group and polygon position remain inside canvas area
* click through transparent area in grouped object
* add some shortcuts for basic usages
* tools button icon in center & switch mode border
* fix load svg image
* basic rtl support, panzoom have issues in rtl mode
* better zoom option both in ltr and rtl
* handle zoom event in mask editor
* add h button to handle toggle mask
* add more mime type
* use capital M (shift+m) for toggle mask
* allow io shortcuts in mask editor only
* make other shapes also remain in canvas bound area
* better zoom implementation, zoom from center
add zoom to resize event listener
* add a border to corner to handle blend of control
* add refresh button to go to selection menu
* add tooltip to shortcuts and also add shortcut for other tools
* make opacity remain in same state when toggled on
* opacity for group/ungroup objects
* update shortcuts implementation
* Revert "Fix I/O not showing in Qt5"
This reverts commit c478689e5a.
* Fix misalignment of IO masks in Qt5 when image is vertically long
Also, as in Qt6, constrain the IO image to fit in the viewport.
* Allow setting occlusion mask border to zero
* Switch to multi-line if statements
cf. 9740393d72
* Enforce if statement braces in dprint
---------
Co-authored-by: Glutanimate <glutanimate@users.noreply.github.com>
* Simplify handling of occlusion types in editor code
- Unify updateIONoteInEditMode(), setOcclusionFieldInner() and
setOcclusionField() into updateOcclusionsField()
- Don't use `includeInactive` property of Shape class in editor code
- Drop `isEditMode`
+
Update the occlusions field every time a mask or text is updated, not
only in editing mode but also in adding mode, so that IO cards can be
previewed correctly in the card layout screen
* Indicate current occlusion type in pop-up menu
https://forums.ankiweb.net/t/anki-23-10-beta-5-6/35677/46
* Fix a11y warnings in Toolbar.svelte
* Drop `occludeInactive` parameter from `MaskEditorAPI.getShapes()`
* Add simple mask editor add-on API
* Signal completed mask editor image loading to Python
* Add API methods for querying mask editor state, fix formatting
* Use event forwarding to propagate image loaded event
Should fix mobile support by moving all bridgeCommand calls to `NoteEditor.svelte`
* Add shape classes to mask editor API
---------
Co-authored-by: Glutanimate <glutanimate@users.noreply.github.com>
* Refactor: Add index to shapes package
* Add shape draw callback API to setupImageCloze
* Expose IO drawing API, switch away from image cloze naming
We currently use "image occlusion" in most places, but some references to "image cloze" still remain. For consistency's sake and to make it easier to quickly find IO-related code, this commit replaces all remaining references to "image cloze", only maintaining those required for backwards compatibility with existing note types.
* Add cloze ordinal to shapes
* Do not mutate original shapes during (de)normalization
Mutating shapes would be a recipe for trouble when combined with IO API use by external consumers.
(makeNormal(makeAbsolute(makeNormal())) is not idempotent,
and keeping track of the original state would introduce
additional complexity with no discernible performance benefit
or otherwise.)
* Tweak IO API, allowing modifications to ShapeProperties
* Tweak drawShape parameters
* Switch method order
For consistency with previous implementation
* Run Rust formatters
* Simplify position (de)normalization
---------
Co-authored-by: Glutanimate <glutanimate@users.noreply.github.com>
* Revert "Fix selected shapes shifting to canvas origin"
This reverts commit d81b96fed0adb7db2fb9847c52d7cb73f83b4b32.
This introduced a regression where the selection of objects was cleared
when it should not have been. For example, if multiple objects were
selected and the mouse was released while moving them around, the
selection would be cleared.
* Another approach to preventing selected shapes from shifting
Prevent fabric objects from shifting to the wrong position when the
active selection contains multiple objects by calculating their
coordinates relative to the canvas, as in the case of the fabric.Group.
* Add text tool to IO
* Remove unnecessary parentheses
* Fix text objects always grouped
* Remove log
* Fix text objects hidden on back side
* Implement text scaling
* Add inverse text outline
* Warn about IO notes with only text objects
This will result in a different error message than the case where no
objects are added at all though, and the user can bypass the warning.
Maybe this is better to avoid discarding the user's work if they have
spent some time adding text.
* Add isValidType
* Use matches!
* Lock aspect ratio of text objects
* Reword misleading comment
The confusion probably comes from the Fabric docs, which apparently need updating: http://fabricjs.com/docs/fabric.Canvas.html#uniformScaling
* Do not count text objects when calculating current index
* Make text objects respond to size changes
* Fix uniform scaling not working when editing
* Use Arial font
* Escape colons and unify parsing
* Handle scale factor when restricting shape to view
* Use 'cloned'
* Add text background
* Tweak drawShape's params
* Fix polygon not converting correctly to cloze
* Fix first polygon disappearing when creating se...
...cond one during editing
Previously, a fabric object was passed directly to a `Shape` such as
`Rectangle` or `Polygon`, so mutating a non-primitive property of the
shape would lead to mutating the original fabric object as well.
* Commit addition of polygon immediately
Unlike the rect or ellipse tools, when the polygon tool was active,
clicking on the canvas did not fire the `object:removed` event and the
`change` event was not dispatched. As a result, an addition of a polygon
was not saved to the DB when switching to another note or closing the
editor in edit mode without performing an action that dispatched the
`change` event.
Issues:
- The `change` event was not dispatched in MaskEditor.svelte when an
undo/redo was performed. Therefore, if the user then closed the editor
or switched to another note without performing an operation that would
cause the `change` event to be dispatched, the undone or redone changes
were not saved to DB.
- When `IOMode.kind === "edit"` (i.e., Edit Current or Browse), the
beginning of the undo history was a blank canvas, not a canvas with
existing masks. Therefore, if you continued to undo to the beginning of
the history, the masks that existed when you opened the editor would be
lost, and they would not be restored even when you performed a redo.
- In the 'Add' dialog, the undo history was not reset when starting to
create a new IO note after adding an IO note.
Also add a small UI improvement:
The undo/redo buttons are now disabled when there is no action to
undo/redo.
* setup mask editor in note editor
- add image on mask button click (only one time)
- show hide add button for io on notetype change
- hide field in io notetype
- icon for toggle
and replace image
* add update io notes
* Tidy up i/o notetype check and fix error
- Make it a method on editor
- Use .get(), because the setting doesn't exist on older notetypes
- Pass the bool value into the ts code, instead of the enum
* reset io page after adding
* remove adjust function & add target for mask editor
* handle browse mode & merged sidetoolbar and toptoolbar to toolbar
* fix: shape, button click in browse, dropdown menu
* add arrow to add button
* store for handling visiblity of maskeditor
- remove update button in edit mode, implement autoupdate
* update var name
* simplify store
Easier to import from, and allows us to declare the output of the build
action without having to iterate over all the proto filenames. Have
confirmed it doesn't break esbuild's tree shaking.
* Fix .no-reduce-motion missing from graphs spinner, and not being honored
* Begin migration from protobuf.js -> protobuf-es
Motivation:
- Protobuf-es has a nicer API: messages are represented as classes, and
fields which should exist are not marked as nullable.
- As it uses modules, only the proto messages we actually use get included
in our bundle output. Protobuf.js put everything in a namespace, which
prevented tree-shaking, and made it awkward to access inner messages.
- ./run after touching a proto file drops from about 8s to 6s on my machine. The tradeoff
is slower decoding/encoding (#2043), but that was mainly a concern for the
graphs page, and was unblocked by
37151213cd
Approach/notes:
- We generate the new protobuf-es interface in addition to existing
protobuf.js interface, so we can migrate a module at a time, starting
with the graphs module.
- rslib:proto now generates RPC methods for TS in addition to the Python
interface. The input-arg-unrolling behaviour of the Python generation is
not required here, as we declare the input arg as a PlainMessage<T>, which
marks it as requiring all fields to be provided.
- i64 is represented as bigint in protobuf-es. We were using a patch to
protobuf.js to get it to output Javascript numbers instead of long.js
types, but now that our supported browser versions support bigint, it's
probably worth biting the bullet and migrating to bigint use. Our IDs
fit comfortably within MAX_SAFE_INTEGER, but that may not hold for future
fields we add.
- Oneofs are handled differently in protobuf-es, and are going to need
some refactoring.
Other notable changes:
- Added a --mkdir arg to our build runner, so we can create a dir easily
during the build on Windows.
- Simplified the preference handling code, by wrapping the preferences
in an outer store, instead of a separate store for each individual
preference. This means a change to one preference will trigger a redraw
of all components that depend on the preference store, but the redrawing
is cheap after moving the data processing to Rust, and it makes the code
easier to follow.
- Drop async(Reactive).ts in favour of more explicit handling with await
blocks/updating.
- Renamed add_inputs_to_group() -> add_dependency(), and fixed it not adding
dependencies to parent groups. Renamed add() -> add_action() for clarity.
* Remove a couple of unused proto imports
* Migrate card info
* Migrate congrats, image occlusion, and tag editor
+ Fix imports for multi-word proto files.
* Migrate change-notetype
* Migrate deck options
* Bump target to es2020; simplify ts lib list
Have used caniuse.com to confirm Chromium 77, iOS 14.5 and the Chrome
on Android support the full es2017-es2020 features.
* Migrate import-csv
* Migrate i18n and fix missing output types in .js
* Migrate custom scheduling, and remove protobuf.js
To mostly maintain our old API contract, we make use of protobuf-es's
ability to convert to JSON, which follows the same format as protobuf.js
did. It doesn't cover all case: users who were previously changing the
variant of a type will need to update their code, as assigning to a new
variant no longer automatically removes the old one, which will cause an
error when we try to convert back from JSON. But I suspect the large majority
of users are adjusting the current variant rather than creating a new one,
and this saves us having to write proxy wrappers, so it seems like a
reasonable compromise.
One other change I made at the same time was to rename value->kind for
the oneofs in our custom study protos, as 'value' was easily confused
with the 'case/value' output that protobuf-es has.
With protobuf.js codegen removed, touching a proto file and invoking
./run drops from about 8s to 6s.
This closes#2043.
* Allow tree-shaking on protobuf types
* Display backend error messages in our ts alert()
* Make sourcemap generation opt-in for ts-run
Considerably slows down build, and not used most of the time.
Prettier by default tries to preserve whitespace around inline tags,
which can prevent problems such as a space before the period in
'<a>text</a>.':
https://prettier.io/blog/2018/11/07/1.15.0.html#whitespace-sensitive-formatting
Unfortunately only standard HTML block elements are excluded from this
behaviour, so all of our Svelte components are treated the same way, even
if they are block-based, or used in a way where the extra whitespace
doesn't matter. This makes the code somewhat harder to read.
Changing this option does carry the risk that rogue spaces will creep
into our UI in the future as code is formatted, but as there don't appear
to be any such issues with this initial reformat, I think the improved
readability may justify the relatively small risk.
* Store coordinates as ratios of full size
* Use single definition for cappedCanvasSize()
* Move I/O review code into ts/image-occlusion
A bit simpler when it's all in one place.
* Reduce number precision, and round to whole pixels
>>> n=10000
>>> for i in range(1, int(n)): assert i == round(float("%0.4f" % (i/n))*n)
* Minor typing tweak
So, it turns out that typing is mostly broken in ts/image-occlusion.
We're importing from fabric which is a js file without types, so types
like fabric.Canvas are resolving to any.
I first tried switching to `@types/fabric`, which introduced a slew of
typing errors. Wasted a few hours trying to address them, before deciding
to give up on it, since the types were not complete. Then found fabric
has a 6.0 beta that introduces typing, and spent some time with that, but
ran into some new issues as it still seems to be a work in progress.
I think we're probably best off waiting until it's out and stabilized
before sinking more effort into this.
* Refactor (de)serialization of occlusions
To make the code easier to follow/maintain, cloze deletions are now decoded/
encoded into simple data classes, which can then be converted to Fabric objects
and back. The data objects handle converting from absolute/normal positions, and
producing values suitable for writing to text (eg truncated floats).
Various other changes:
- Polygon points are now stored as 'x,y x2,y2 ...' instead of JSON in cloze
divs, as that makes the handling consistent with reading from cloze deletion
text.
- Fixed the reviewer not showing updated placement when a polygon was moved.
- Disabled rotation controls in the editor, since we don't support rotation during
review.
- Renamed hideInactive to occludeInactive, as it wasn't clear whether the former
meant to hide the occlusions, or keep them (hiding the content). It's stored
as 'oi=1' in the cloze text.
* Increase canvas size limit, and double pixels when required.
* Size canvas based on container size
This results in sharper masks when the intrinsic image size is smaller
than the container, and more legible ones when the container is smaller than
the intrinsic image size.
By using the container instead of the viewport, we account for margins,
and when the pixel ratio is 1x, the canvas size and container size should
match.
* Disable zoom animation on editor load
* Default to rectangle when adding new occlusions
* Allow users to add/update notes directly from mask editing page
* The mask editor needs to work with css pixels, not actual pixels
The canvas and image were being scaled too large, which impacted
performance.
* Cloze styling is not required in I/O notetype
* Use raw string for IO template
* Rename to notetype.css and use more specific ids
* Move internal i/o styling into runtime
Storing it in the notetype makes it difficult to make changes, and
makes it easier for the user to break.
* Fix misaligned occlusions
At larger screen sizes, the canvas was not increasing above its configured
size, so it ended up being placed top center instead of expanding to fit
the entire container area.
To resolve this, both the image and canvas are forced to the container
size, and the container is constrained to the size of the viewport,
with the same aspect ratio as the image.
Closes#2492
* Allow user to select I/O notetype instead of enforcing a specific name
* Display a clearer error when I/O note is missing an image
Opening the card layout screen from "manage notetypes" was showing an
error about the Anki version being too old.
Replacement error is not currently translatable.
* Preserve existing notetype when adding I/O notetype
* Add a 'from clipboard' string
The intention is to use this in the future to allow an image occlusion
to be created from an image on the clipboard.
* Tweak I/O init
- Use union type instead of multiple nullable values
- Pass the notetype id in to initialization
* Fix image insertion in I/O note
- The regex expected double quotes, and we were using single ones
- Image tags don't need to be closed
* Use more consistent naming in image_occlusion.proto
* Tweaks to default I/O notetype
- Show the header on the front side as well (I presume this is what
users expect; if not am happy to revert)
- Don't show comments on card (again, I presume users expect to use
this field to add notes that aren't displayed during review, as they
can use back extra for that)
* Fix sticky footer missing background
Caused by earlier CSS refactoring
* add note types with occlusions and image fields
* generate image occlusion cloze div data
- generate div element with data-* atrributes for canvas shape generate for reviewer
* getting image data & deck id and adding notes
the implementation added into backend
- added service index in backend.proto for image occlusion request
- created image_occlusion.proto with required message and service
- implementation in backend for getting image and adding notes, also during editing return imagecloze note and update notes
- add notes to selected deck, if no notetype then add image occlusion notetypes
- reuse notetype from stock notetypes when not exist
* script for generating shapes using canvas api in reviewer
- the flash issues fixed by loading image and using image size to draw canvas, also when image get resized, calculate scale using natural width and canvas width to draw shape at right position
- limit size of canvas for safari
* init image occlusion page in ts and build page
with
- fabricjs for editing shapes
- panzoom for drag and zoom
- pickr for color picker
- build page using web.rs
* implement top toolbar for canvas shapes
- undo & redo tools
- zoom in, zoom out and zoom fit
- group & ungroup
- copy & paste
- set transparency of shapes
- align tools
* implement side toolbar for drawing shapes
add top toolbar and the side toolbar contains following tools
- cursor for selecting shapes
- zoom for drag and zoom shapes in mask editor
- rectangle for creating it
- ellipse for creating it
- polygon for creating it using points
- shape fill color
- question mask color (currently only single color can be added for all shapes)
* add maskeditor page for editing mask
- add side toolbar and sidebar include toptoolbar
- load maskeditor in two mode
- for adding note using path to image
- for editing note using note id
* implement note editor page for adding notes
- the note editor page have simple button (B/I/U) and option to toggle html view
- option to select deck for adding notes into that deck
- option to generate to hide all, guess one & hide one, guess one notes
* add image occlusion page
add side toolbar, top toolbar, mask editor and note editor
- option to switch between mask editor and note editor
* implement generates notes and save notes
implemention to show toast components for messages
* removed pickr & implemented color picker component
- remove pickr
- implemented using html5 canvas
- range input for changing color
- another range input for opacity changes
- hex and rgba value support
* rename methods name & rust unwrap safety
- change plural names to singular
- create respone message in proto and return response with imagecloze note or error if not found with note id
- remove image_occlusion from post handler list
- rename service name in mediasrv.py
- rename methods name for image occlusion in backend and image_occlusion
- update frontend also for update functions' names
- handle error in frontend mask-editor.ts, when error getting notes then toast message shown to frontend
* extract to function & add comments & remove global
- extract function in mask-editor.ts to reduce duplicate
- remove unused global from css
- add comments to store.ts explaining usage
- changes id to noteId in lib.ts
- add comments for limitSize, becuase of duplicate implementation
* remove image_occlusion notetype
- remove from stock notetype, stdmodels
- add implementation for notetype to image occlusion
- add i18n for errors
* update smooth scroll, always show cursor tools
- change questionmask to qmask
- make selectable for shape true in all tools to simplify edits and draw shapes
- update image occlusion in reviewer ts to load image properly
* add and get notetype else return errors
* fix: not showing occlusion
* Use a oneof for ImageClozeNoteResponse
Makes it clearer that only one of them can be returned
* Don't crash if image filename not provided
The second unwrap should be ok, as the input is utf8
* Refactor get_image_cloze_note
- fixes crash when note doesn't exist - Ok(None) case was not covered
- decouples business logic from native error->proto error conversion
- no need for original copy
- field[x] is more idiomatic than field.get(x).unwrap()
- don't need mutable access to fields
* Fix crash if image file unreadable
+ Use our read_file helper for better error context
* Add metadata() helper
* Fix crash if file metadata can't be read
* remove color picker, qmask and shape color
- remove strings from ftl
- remove color picker component
- remove from cloze generation
- remove icons for two buttons
- use constant color for shapes
* update color in reviewer and ftl strings
* fix shape position in canvas & add border to shape
- rename mask to inactive shape and active shape color
- border witdth and border color
- change decimal point deserializing string and toFixed(2)
- add thin border in mask editor, may be image background was transparent
* fix shape position in canvas after modified
- do not draw fixed ratio shapes by turn of uniformScaling
- fix rectangle width,height
- fix ellipse rx,ry,width,height
- fix polygon postion and points
- draw outside of canvas also
* fix border width and color in reviewer canvas
- rename variable
* refactor cloze div generate and remove angle
* fix origin when drawn outside of canvas from right
* fix shape at boundry & not include rx,ry rectangle
- move shapes at boundry when pointer is outside of canvas
- include rx, ry for ellipse only
- include points for polygon only
* fix lint errors & update image size in editor canvas based on height and width
* remove unsupported layerX & layerX for touchscreen
- fix shapes at edges
* implemented undo redo with canvas state
- implemented undo redo using fabric canvas events
- polygon is special case and implemented only added and modified event
- rectangle and ellipse have object:added, object:modified and object:removed case
- change id to undo and redo
* remove background image from canvas and used css to put image tag below canvas editor
- set image width and height after adding image
* fix for polygon points, add br in cloze strings, & toogle masks button
- fix shapes at edges
- toggle masks button to show/hide masks
- hide clozes string, it contains <br>
- set height for div container (used 'relative' in css)
* refactor top toolbar, add space and border radius
- rename cursor tools
- add left and right border
* fix undo after undo happen, use transparent color in draw mode