diff --git a/README.md b/README.md index d1aedb4..1052e32 100644 --- a/README.md +++ b/README.md @@ -230,3 +230,7 @@ As an exception, `dep/snowhouse` contains the snowhouse assertion library, taken from https://github.com/banditcpp/snowhouse. It is Boost Standard License 1.0 licensed. Please see the contents of the directory for the full text. +As an exception, `dep/libui` contains the libui GUI library, taken from +https://github.com/andlabs/libui. It is MIT licensed. Please see the contents +of the directory for the full text. + diff --git a/dep/libui/CONTRIBUTING.md b/dep/libui/CONTRIBUTING.md new file mode 100644 index 0000000..94bd199 --- /dev/null +++ b/dep/libui/CONTRIBUTING.md @@ -0,0 +1,131 @@ +# Contributing to libui + +libui is an open source project that openly accepts contributions. I appreciate your help! + +## Rules for contributing code + +While libui is open to contributions, a number of recent, significantly large contributions and uncontributed forks have recently surfaced that do not present themselves in a form that makes it easy for libui to accept them. In order to give your contribution a high chance of being accepted into libui, please keep the following in mind as you prepare your contribution. + +### Commit messages and pull request description + +libui does not enforce rules about the length or detail that a commit message. I'm not looking for an essay. However, single-word descriptions of nontrivial changes are *not* acceptable. I should be able to get a glimpse of what a commit does from the commit message, even if it's just one sentence to describe a trivial change. (Yes, I know I haven't followed this rule strictly myself, but I try not to break it too.) And a commit message should encompass everything; typically, I make a number of incremental commits toward a feature, so the commit messages don't have to be too long to explain everything. + +Your pull request description, on the other hand, must be a summary of the sum total of all the changes made to libui. Don't just drop a pull request on me with a one-line-long elevator pitch of what you added. Describe your proposed API changes, implementation requirements, and any important consequences of your work. + +### Code formatting + +libui uses K&R C formatting rules for overall code structure: spaces after keywords like `if`, `{` on the same line as a statement with a space, `{` on its own line after a function or method signature (even those inside the class body), no space after the name of a function, etc. + +Use hard tabs, NOT spaces, for indentation. I use a proportional-width font and my text editor doesn't set tabs to a multiple of the space width, so I *will* be able to tell. If you use a fixed-width font, I suggest setting a tab width of 4 spaces per tab, but don't put diagrams in comments with hard tabs, because not everyone does this. + +Expressions should have a space around binary operators, and use parentheses where it would help humans gather the meaning of an expression, regardless of whether a computer could tell what is correct. + +When breaking expressions into multiple lines, always break *after* an operator, such as `,` or `&&`. + +There should be a newline between a function's variables and a function's code. After that, you can place newlines to delimit different parts of a function, but don't go crazy. + +In the event you are unsure of something, refer to existing libui code for examples. I may wind up fixing minor details later anyway, so don't fret about getting minor details right the first time. + +### Naming + +libui uses camel-case for naming, with a handful of very specific exceptions (namely GObject method names, where GObject itself enforces the naming convention). + +All public API names should begin with `ui` and followed by a capital letter. All public struct field names should begin with a capital letter. This is identical to the visibiilty rules of Go, assuming a package name of `ui`. + +Private API names — specifcally those used by more than one source file — should begin with `uipriv` and be followed by a capital letter. This avoids namespace collisions in static libraries. + +Static functions and static objects do not have naming restrictions. + +Acronyms should **NOT** be mixed-case. `http` for the first word in a camel-case name, `HTTP` for all else, but **NEVER** `Http`. This is possibly the only aspect of the controversial nature of code style that I consider indefensibly stupid. + +### API documentation + +(TODO I am writing an API documentation tool; once that becomes stable enough I can talk about documenting libui properly. You'll see vestiges of it throughout ui.h, though.) + +### Other commenting + +(TODO write this part) + +### Compatibility + +libui takes backward compatibility seriously. Your code should not break the current compatibility requirements. All platforms provide a series of macros, defined in the various `uipriv_*.h` files (or `winapi.hpp` on Windows), that specify the minimum required version. If you find yourself needing to remove these or ignore resultant warnings or errors, you're probably breaking compatibility. + +Choosing to drop older versions of Windows, GTK+, and OS X that I could have easily continued to support was not done lightly. If you want to discuss dropping support for an older version of any of these for the benefit of libui, file an issue pleading your case (see below). + +GTK+ versions are harder to drop because I am limited by Linux distribution packaging. In general, I will consider bumping GTK+ versions on a new Ubuntu LTS release, choosing the earliest version available on the major distributions at the time of the *previous* Ubuntu LTS release. As of writing, the next milestone will be *after* April 2018, and the target GTK+ version appears to be 3.18, judging by Ubuntu 16.04 LTS alone. This may be bumped back depending on other distros (or it may not be bumped at all), but you may wish to keep this in mind as you write. + +(TODO talk about future.c/.cpp/.m files) + +As for language compatibility, libui is written in C99. I have no intention of changing this. + +As for build system compatibility, libui uses CMake 3.1.0. If you wish to bump the version, file an issue pleading your case (but see below). + +**If you do plead your case**, keep in mind that "it's old" is not a sufficient reason to drop things. If you can prove that **virtually no one** uses the minimum version anymore, then that is stronger evidence. The best evidence, however, is that not upgrading will hold libui back in some significant way — but beware that there are some things I won't add to libui itself. + +### Windows-specific notes + +The Windows backend of libui is written in C++ using C++11. + +Despite using C++, please refrain from using the following: + +- using C++ in ui_windows.h (this file should still be C compatible) +- smart pointers +- namespaces +- `using namespace` +- ATL, MFC, WTL + +The following are not recommended, for consistency with the rest of libui: + +- variable declarations anywhere in a function (keep them all at the top) +- `for (int x...` (C++11 foreach syntax is fine, though) +- omitting the `struct` on type names for ordinary structs + +The format of a class should be + +```c++ +class name : public ancestor { + int privateVariable; + // etc. +public: + // public stuff here +}; +``` + +### GTK+-specific notes + +Avoid GNU-specific language features. I build with strict C99 conformance. + +### OS X-specific notes + +Avoid GNU-specific/clang-specific language features. I build with strict C99 conformance. + +libui is presently **not** ARC-compliant. Features that require ARC should be avoided for now. I may consider changing this in the future, but it will be a significant change. + +To ensure maximum compiler output in the event of a coding error, there should not be any implicit method calls in Objective-C code. For instance, don't do + +```objective-c +[[array objectAtIndex:i] method] +``` + +Instead, cast the result of `objectAtIndex:` to the appropriate type, and then call the method. (TODO learn about, then decide a policy on, soft-generics on things other than `id`) + +The format of a class should be + +```objective-c +@interface name : parent { + // ivars +} +// properties +- (ret)method:(int)arg; +// more methods +@end + +@implementation name + +- (ret)method:(int)arg +{ + // note the lack of semicolon +} + +@end +``` diff --git a/dep/libui/Compatibility.md b/dep/libui/Compatibility.md new file mode 100644 index 0000000..bc16f1b --- /dev/null +++ b/dep/libui/Compatibility.md @@ -0,0 +1,141 @@ +# Useful things in newer versions + +## Windows +### Windows 7 +http://channel9.msdn.com/blogs/pdc2008/pc43 + +TODO look up PDC 2008 talk "new shell user interface" + +- new animation and text engine +- ribbon control (didn't this have some additional license?) +- LVITEM.piColFmt + +### Windows 8 + +### Windows 8.1 + +### Windows 10 + +## GTK+ +TODO what ships with Ubuntu Quantal (12.10)? + +### GTK+ 3.6 +ships with: Ubuntu Raring (13.04) + +- GtkEntry and GtkTextView have input purposes and input hints for external input methods but do not change input themselves + - according to Company, we connect to insert-text for that +- GtkLevelBar +- GtkMenuButton +- **GtkSearchEntry** + +### GTK+ 3.8 +ships with: Ubuntu Saucy (13.10) + +Not many interesting new things to us here, unless you count widget-internal tickers and single-click instead of double-click to select list items (a la KDE)... and oh yeah, also widget opacity. + +### GTK+ 3.10 +ships with: **Ubuntu Trusty (14.04 LTS)** +
GLib version: 2.40 + +- tab character stops in GtkEntry +- GtkHeaderBar + - intended for titlebar overrides; GtkInfoBar is what I keep thinking GtkHeaderBar is +- **GtkListBox** +- GtkRevealer for smooth animations of disclosure triangles +- GtkSearchBar for custom search popups +- **GtkStack and GtkStackSwitcher** +- titlebar overrides (seems to be the hot new thing) + +### GTK+ 3.12 +ships with: Ubuntu Utopic (14.10) +
GLib version: 2.42 + +- GtkActionBar (basically like the bottom-of-the-window toolbars in Mac programs) +- gtk_get_locale_direction(), for internationalization +- more control over GtkHeaderBar +- **GtkPopover** + - GtkPopovers on GtkMenuButtons +- GtkStack signaling +- **gtk_tree_path_new_from_indicesv()** (for when we add Table if we have trees too) + +### GTK+ 3.14 +ships with: **Debian Jessie**, Ubuntu Vivid (15.04) +
GLib version: Debian: 2.42, Ubuntu: 2.44 + +- gestures +- better GtkListbox selection handling +- more style classes (TODO also prior?) +- delayed switch changes on GtkSwitch + +### GTK+ 3.16 +ships with: Ubuntu Wily (15.10) +
GLib version: 2.46 + +- gtk_clipboard_get_default() (???) +- **GtkGLArea** +- proper xalign and yalign for GtkLabel; should get rid of runtime deprecation warnings +- better control of GtkListBox model-based creation (probably not relevant but) +- GtkModelButton (for GActions; probably not relevant?) +- wide handles on GtkPaned +- GtkPopoverMenu +- IPP paper names in GtkPaperSize (TODO will this be important for printing?) +- multiple matches in GtkSearchEntry (TODO evaluate priority) +- **GtkStackSidebar** +- GTK_STYLE_CLASS_LABEL, GTK_STYLE_CLASS_MONOSPACE, GTK_STYLE_CLASS_STATUSBAR, GTK_STYLE_CLASS_TOUCH_SELECTION, GTK_STYLE_CLASS_WIDE (TODO figure out which of these are useful) +- GtkTextView: extend-selection +- GtkTextView: font fallbacks + +### GTK+ 3.18 + +### GTK+ 3.20 + +## Cocoa +### Mac OS X 10.8 + +- Foundation ([full details](https://developer.apple.com/library/mac/releasenotes/Foundation/RN-FoundationOlderNotes/#//apple_ref/doc/uid/TP40008080-TRANSLATED_CHAPTER_965-TRANSLATED_DEST_999B)) + - NSDateComponents supports leap months + - NSNumberFormatter and NSDateFormatter default to 10.4 behavior by default (need to explicitly do this on 10.7) + - **NSUserNotification and NSUserNotificationCenter for Growl-style notifications** + - better linguistic triggers for Spanish and Italian + - NSByteCountFormatter +- AppKit ([full details](https://developer.apple.com/library/mac/releasenotes/AppKit/RN-AppKitOlderNotes/#X10_8Notes)) + - view-based NSTableView/NSOutlineView have expansion tooltips + - NSScrollView magnification + - Quick Look events; TODO see if they conflict with keyboard handling in Area + - NSPageController (maybe useful?) + - not useful for package UI, but may be useful for a new library (probably not by me): NSSharingService + - NSOpenPanel and NSSavePanel are now longer NSPanels or NSWindows in sandboxed applications; this may be an issue should anyone dare to enable sandboxing on a program that uses package ui + - NSTextAlternatives + - -[NSOpenGLContext setFullScreen] now ineffective + - +[NSColor underPageBackgroundColor] + +### Mac OS X 10.9 + +- Foundation ([full details](https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/)) + - system-provided progress reporting/cancellation support + - NSURLComponents + - **NSCalendar, NSDateFormatter, and NSNumberFormatter are now thread-safe** + - various NSCalendar and NSDateComponents improvements +- AppKit ([full details](https://developer.apple.com/library/mac/releasenotes/AppKit/RN-AppKit/)) + - sheet handling is now block-based, queued, and in NSWindow; the delegate-based NSApplication API will still exist, except without the queue + - similar changes to NSAlert + - **return value changes to NSAlert** + - window visibility APIs (occlusion) + - NSApplicationActivationPolicyAccessory + - fullscreen toolbar behavior changes + - status items for multiple menu bars + - better NSSharingService support + - a special accelerated scrolling mode, Responsive Scrolling; won't matter for us since I plan to support the scroll wheel and it won't + - NSScrollView live scrolling notifications + - NSScrollView floating (anchored/non-scrolling) subviews + - better multimonitor support + - better key-value observing for NSOpenPanel/NSSavePanel (might want to look this up to see if we can override some other juicy details... TODO) + - better accessory view key-view handling in NSOpenPanel/NSSavePanel + - NSAppearance + - **-[NSTableView moveRowAtIndex:toIndex:] bug regarding first responders fixed** + - view-specific RTL overrides + +### Mac OS X 10.10 + +### Mac OS X 10.11 +* **NSLayoutGuide** diff --git a/dep/libui/LICENSE b/dep/libui/LICENSE new file mode 100644 index 0000000..2351d66 --- /dev/null +++ b/dep/libui/LICENSE @@ -0,0 +1,9 @@ +Copyright (c) 2014 Pietro Gagliardi + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +(this is called the MIT License or Expat License; see http://www.opensource.org/licenses/MIT) diff --git a/dep/libui/NEWS.md b/dep/libui/NEWS.md new file mode 100644 index 0000000..d439ed4 --- /dev/null +++ b/dep/libui/NEWS.md @@ -0,0 +1,113 @@ +# Old News + +* **27 November 2016** + * Decided to split the table stuff into its own branch. It will be developed independently of everything else, along with a few other features. + +* **2 November 2016** + * Added two new functions to replace the deleted `uiWindowPosition()` and friends: `uiAreaBeginUserWindowMove()` and `uiAreaBeginUserWindowResize()`. When used in a `uiAreaHandler.Mouse()` event handler, these let you initiate a user-driven mouse move or mouse resize of the window at any point in a uiArea. + +* **31 October 2016** + * @krakjoe noticed that I accidentally used thread-unsafe code in uiQueueMain() on Unix. Fixed. + +* **24 October 2016** + * `uiWindowSetContentSize()` on Unix no longer needs to call up the GTK+ main loop. As a result, bugs related to strange behavior using that function (and the now-deleted `uiWindowSetPosition()` and `uiWindowCenter()`) should go away. I'll need to go through the bugs to verify as much, though. + +* **22 October 2016** + * Due to being unable to guarantee they will work (especially as we move toward capability-driven window systems like Wayland), or being unable to work without hacking that breaks other things, the following functions have been removed: `uiWindowPosition()`, `uiWindowSetPosition()`, `uiWindowCenter()`, and `uiWindowOnPositionChanged()`. Centering may come back at some point in the future, albeit in a possibly restricted form. A function to initiate a user move when a part of a uiArea is clicked will be provided soon. + +* **21 October 2016** + * `uiDrawTextWeightUltraBold` is now spelled correctly. Thanks to @krakjoe. + +* **18 June 2016** + * Help decide [the design of tables and trees in libui](https://github.com/andlabs/libui/issues/159); the implementation starts within the next few days, if not tomorrow! + +* **17 June 2016** + * **CMake 3.1.0 is now required.** This is due to CMake's rapid development pace in the past few years adding things libui needs to build on as many systems as possible. If your OS is supported by libui but its repositories ship with an older version of CMake, you will need to find an updated one somewhere. + * Please help [plan out a better menu API](https://github.com/andlabs/libui/issues/152). + * `uiMainSteps()` no longer takes any arguments and no longer needs to invoke a function to do the work. You still need to call it, but once you do, it will return immediately and you can then get right to your main loop. + * **CMake 3.1.0 is now required.** This is due to CMake's rapid development pace in the past few years adding things libui needs to build on as many systems as possible. If your OS is supported by libui but its repositories ship with an older version of CMake, you will need to find an updated one somewhere. + * Added `uiNewVerticalSeparator()` to complement `uiNewHorizontalSeparator()`. + +* **16 June 2016** + * Added `uiWindowContentSize()`, `uiWindowSetContentSize()`, and `uiWindowOnContentSizeChanged()` methods for manipulating uiWindow content sizes. Note the use of "content size"; the size you work with does NOT include window decorations (titlebars, menus, etc.). + * Added `uiWindowFullscreen()` and `uiWindowSetFullscreen()` to allow making fullscreen uiWindows, taking advantage of OS facilities for fullscreen and without changing the screen resolution (!). + * Added `uiWindowBorderless()` and `uiWindowSetBorderless()` for allowing borderless uiWindows. + * Added `uiMainSteps()`. You call this instead of `uiMain()` if you want to run the main loop yourself. You pass in a function that will be called; within that function, you call `uiMainStep()` repeatedly until it returns 0, doing whatever you need to do in the meantime. (This was needed because just having `uiMainStep()` by itself only worked on some systems.) + * Added `uiProgressBarValue()` and allowed passing -1 to `uiProgressBarSetValue()` to make an indeterminate progress bar. Thanks to @emersion. + +* **15 June 2016** + * Added `uiFormDelete()`; thanks to @emersion. + * Added `uiWindowPosition()`, `uiWindowSetPosition()`, `uiWindowCenter()`, and `uiWindowOnPositionChanged()`, methods for manipulating uiWindow position. + +* **14 June 2016** + * uiDarwinControl now has a `ChildVisibilityChanged()` method and a corresponding `NotifyVisibilityChanged()` function that is called by the default show/hide handlers. This is used to make visibility changes work on OS X; uiBox, uiForm, and uiGrid all respect these now. + * The same has been done on the Windows side as well. + * Hiding and showing controls and padding calculations are now correct on Windows at long last. + * Hiding a control in a uiForm now hides its label on all platforms. + +* **13 June 2016** + * `intmax_t` and `uintmax_t` are no longer used for libui API functions; now we use `int`. This should make things much easier for bindings. `int` should be at least 32 bits wide; this should be sufficient for all but the most extreme cases. + +* **12 June 2016** + * Added `uiGrid`, a new container control that arranges controls in rows and columns, with stretchy ("expanding") rows, stretchy ("expanding") columns, cells that span rows and columns, and cells whose content is aligned in either direction rather than just filling. It's quite powerful, is it? =P + +* **8 June 2016** + * Added `uiForm`, a new container control that arranges controls vertically, with properly aligned labels on each. Have fun! + +* **6 June 2016** + * Added `uiRadioButtonsSelected()`, `uiRadioButtonsSetSelected()`, and `uiRadioButtonsOnSelected()` to control selection of a radio button and catch an event when such a thing happens. + +* **5 June 2016** + * **Alpha 3.1 is here.** This was a much-needed update to Alpha 3 that changes a few things: + * **The build system is now cmake.** cmake 2.8.11 or higher is needed. + * Static linking is now fully possible. + * MinGW linking is back, but static only. + * Added `uiNewPasswordEntry()`, which creates a new `uiEntry` suitable for entering passwords. + * Added `uiNewSearchEntry()`, which creates a new `uiEntry` suitable for searching. On some systems, the `OnChanged()` event will be slightly delayed and/or combined, to produce a more natural feel when searching. + +* **29 May 2016** + * **Alpha 3 is here!** Get it [here](https://github.com/andlabs/libui/releases/tag/alpha3). + * The next packaged release will introduce: + * uiGrid, another way to lay out controls, a la GtkGrid + * uiOpenGLArea, a way to render OpenGL content in a libui uiArea + * uiTable, a data grid control that may or may not have tree facilities (if it does, it will be called uiTree instead) + * a complete, possibly rewritten, drawing and text rendering infrastructure + * Thanks to @pcwalton, we can now statically link libui! Simply do `make STATIC=1` instead of just `make`. + * On Windows you must link both `libui.lib` and `libui.res` AND provide a Common Controls 6 manifest for output static binaries to work properly. + +* **28 May 2016** + * As promised, **the minimum system requirements are now OS X 10.8 and GTK+ 3.10 for OS X and Unix, respectively**. + +* **26 May 2016** + * Two OS X-specific functions have been added: `uiDarwinMarginAmount()` and `uiDarwinPaddingAmount()`. These return the amount of margins and padding, respectively, to give to a control, and are intended for container implementations. These are suitable for the constant of a NSLayoutConstraint. They both take a pointer parameter that is reserved for future use and should be `NULL`. + +* **25 May 2016** + * uiDrawTextLayout attributes are now specified in units of *graphemes* on all platforms. This means characters as seen from a user's perspective, not Unicode codepoints or UTF-8 bytes. So a long string of combining marker codepoints after one codepoint would still count as one grapheme. + +* **24 May 2016** + * You can now help choose [a potential new build system for libui](https://github.com/andlabs/libui/issues/62). + * Tomorrow I will decide if OS X 10.7 will also be dropped alongside GTK+ 3.4-3.8 this Saturday. Stay tuned. + * As promised, `uiCombobox` is now split into `uiCombobox` for non-editable comboboxes and `uiEditableCombobox` for editable comboboxes. Mind the function changes as well :) + * There is a new function `uiMainStep()`, which runs one iteration of the main loop. It takes a single boolean argument, indicating whether to wait for an event to occur or not. It returns true if an event was processed (or if no event is available if you don't want to wait) and false if the event loop was told to stop (for instance, `uiQuit()` was called). + +* **23 May 2016** + * Fixed surrogate pair drawing on OS X. + +* **22 May 2016** + * Two more open questions I'd like your feedback on are available [here](https://github.com/andlabs/libui/issues/48) and [here](https://github.com/andlabs/libui/issues/25). + * Sometime in the next 48 hours (before 23:59 EDT on 24 May 2016) I will split `uiCombobox` into two separate controls, `uiCombobox` and `uiEditableCombobox`, each with slightly different events and "selected item" mechanics. Prepare your existing code. + * Removed `uiControlVerifyDestroy()`; that is now part of `uiFreeControl()` itself. + * Added `uiPi`, a constant for π. This is provided for C and C++ programmers, where there is no standard named constant for π; bindings authors shouldn't need to worry about this. + * Fixed uiMultilineEntry not properly having line breaks on Windows. + * Added `uiNewNonWrappingMultilineEntry()`, which creates a uiMultilineEntry that scrolls horizontally instead of wrapping lines. (This is not documented as being changeable after the fact on Windows, hence it's a creation-time choice.) + * uiAreas on Windows and some internal Direct2D areas now respond to `WM_PRINTCLIENT` properly, which should hopefully increase the quality of screenshots. + * uiDateTimePicker on GTK+ works properly on RTL layouts and no longer disappears off the bottom of the screen if not enough room is available. It will also no longer be marked for localization of the time format (what the separator should be and whether to use 24-hour time), as that information is not provided by the locale system. :( + * Added `uiUserBugCannotSetParentOnToplevel()`, which should be used by implementations of toplevel controls in their `SetParent()` implementations. This will also be the beginning of consolidating common user bug messages into a single place, though this will be one of the only few exported user bug functions. + * uiSpinbox and uiSlider now merely swap their min and max if min ≥ max. They will no longer panic and do nothing, respectively. + * Matrix scaling will no longer leave the matrix in an invalid state on OS X and GTK+. + * `uiMultilineEntrySetText()` and `uiMutlilineEntryAppend()` on GTK+ no longer fire `OnChanged()` events. + +* **21 May 2016** + * I will now post announcements and updates here. + * Now that Ubuntu 16.04 LTS is here, no earlier than next Saturday, 28 May 2016 at noon EDT, **I will bump the minimum GTK+ version from 3.4 to 3.10**. This will add a lot of new features that I can now add to libui, such as search-oriented uiEntries, lists of arbitrary control layouts, and more. If you are still running a Linux distribution that doesn't come with 3.10, you will either need to upgrade or use jhbuild to set up a newer version of GTK+ in a private environment. + * You can decide if I should also drop OS X 10.7 [here](https://github.com/andlabs/libui/issues/46). diff --git a/dep/libui/README.md b/dep/libui/README.md new file mode 100644 index 0000000..8cdf89b --- /dev/null +++ b/dep/libui/README.md @@ -0,0 +1,195 @@ +# libui: a portable GUI library for C + +This README is being written.
+[![Build Status, Azure Pipelines](https://dev.azure.com/andlabs/libui/_apis/build/status/andlabs.libui?branchName=master)](https://dev.azure.com/andlabs/libui/_build/latest?definitionId=1&branchName=master)
+[![Build Status, AppVeyor](https://ci.appveyor.com/api/projects/status/ouyk78c52mmisa31/branch/master?svg=true)](https://ci.appveyor.com/project/andlabs/libui/branch/master) + +## Status + +It has come to my attention that I have not been particularly clear about how usable or feature-complete libui is, and that this has fooled many people into expecting more from libui right this moment than I have explicitly promised to make available. I apologize for not doing this sooner. + +libui is currently **mid-alpha** software. Much of what is currently present runs stabily enough for the examples and perhaps some small programs to work, but the stability is still a work-in-progress, much of what is already there is not feature-complete, some of it will be buggy on certain platforms, and there's a lot of stuff missing. In short, here's a list of features that I would like to add to libui, but that aren't in yet: + +- trees +- clipboard support, including drag and drop +- more and better dialogs +- printing +- accessibility for uiArea and custom controls +- document-based programs +- tighter OS integration (especially for document-based programs), to allow programs to fully feel native, rather than merely look and act native +- better support for standard dialogs and features (search bars, etc.) +- OpenGL support + +In addition, [here](https://github.com/andlabs/libui/issues?utf8=%E2%9C%93&q=master+in%3Atitle+is%3Aissue+is%3Aopen) is a list of issues generalizing existing problems. + +Furthermore, libui is not properly fully documented yet. This is mainly due to the fact that the API was initially unstable enough so as to result in rewriting documentation multiple times, in addition to me not being happy with really any existing C code documentation tool. That being said, I have started to pin down my ideal code documentation style in parts of `ui.h`, most notably in the uiAttributedString APIs. Over time, I plan on extending this to the rest of the headers. You can also use [the documentation for libui's Go bindings](https://godoc.org/github.com/andlabs/ui) as a reference, though it is somewhat stale and not optimally written. + +But libui is not dead; I am working on it whenever I can, and I hope to get it to a point of real quality soon! + +## News + +*Note that today's entry (Eastern Time) may be updated later today.* + +* **7 April 2019** + * **The build system has been switched to Meson.** See below for instructions. This change was made because the previous build system, CMake, caused countless headaches over trivial issues. Meson was chosen due to how unproblematic setting up libui's build just right was, as well as having design goals that are by coincidence closely aligned with what libui wants. + * Travis CI has been replaced with Azure Pipelines and much of the AppVeyor CI configuration was integrated into the Azure Pipelines configuration. This shouldn't affect most developers. + +* **1 September 2018** + * **Alpha 4.1 is here.** This is an emergency fix to Alpha 4 to fix `uiImageAppend()` not working as documented. It now works properly, with one important difference you'll need to care about: **it now requires image data to be alpha-premultiplied**. In addition, `uiImage` also is implemented slightly more nicely now, and `ui.h` has minor documentation typo fixes. + * Alpha 4.1 also tries to make everything properly PIC-enabled. + +* **10 August 2018** + * **Alpha 4 is finally here.** Everything from Alpha 3.5 and what's listed below is in this release; the two biggest changes are still the new text drawing API and new uiTable control. In between all that is a whole bunch of bugfixes, and hopefully more stability too. Thanks to everybody who helped contribute! + * Alpha 4 should hopefully also include automated binary releases via CI. Thanks to those who helped set that up! + +* **8 August 2018** + * Finally introduced an API for loading images, `uiImage`, and a new control, `uiTable`, for displaying tabular data. These provide enough basic functionality for now, but will be improved over time. You can read the documentation for the new features as they are [here](https://github.com/andlabs/libui/blob/f47e1423cf95ad7b1001663f3381b5a819fc67b9/uitable.h). Thanks to everyone who helped get to this point, in particular @bcampbell for the initial Windows code, and to everyone else for their patience! + +* **30 May 2018** + * Merged the previous Announcements and Updates section of this README into a single News section, and merged the respective archive files into a single NEWS.md file. + +* **16 May 2018** + * Thanks to @parro-it and @msink, libui now has better CI, including AppVeyor for Windows CI, and automated creation of binary releases when I make a tagged release. + +* **13 May 2018** + * Added new functions to work with uiDateTimePickers: `uiDateTimePickerTime()`, `uiDateTimePickerSetTime()`, and `uiDateTimePickerOnChanged()`. These operate on standard `` `struct tm`s. Thanks @cody271! + * Release builds on Windows with MSVC should be fixed now; thanks @l0calh05t, @slahn, @mischnic, and @zentner-kyle. + +* **12 May 2018** + * GTK+ and OS X now have a cleaner build process for static libraries which no longer has intermediate files and differing configurations. As a result, certain issues should no longer be present. New naming rules for internal symbols of libui have also started being drafted; runtime symbols and edge cases still need to be handled (and the rules applied to Windows) before this can become a regular thing. + +* **2 May 2018** + * On Windows, you no longer need to carry around a `libui.res` file with static builds. You do need to link in the appropriate manifest file, such as the one in the `windows/` folder (I still need to figure out exactly what is needed apart from the Common Controls v6 dependency, or at least to create a complete-ish template), or at least include it alongside your executables. This also means you should no longer see random cmake errors when building the static libraries. + +* **18 April 2018** + * Introduced a new `uiTimer()` function for running code on a timer on the main thread. (Thanks to @cody271.) + * Migrated all code in the `common/` directory to use `uipriv` prefixes for everything that isn't `static`. This is the first step toward fixing static library oddities within libui, allowing libui to truly be safely used as either a static library or a shared library. + +* **18 March 2018** + * Introduced an all-new formatted text API that allows you to process formatted text in ways that the old API wouldn't allow. You can read on the whole API [here](https://github.com/andlabs/libui/blob/8944a3fc5528445b9027b1294b6c86bae03eeb89/ui_attrstr.h). There is also a new examples for it: `drawtext`, which shows the whole API at a glance. It doesn't yet support measuring or manipulating text, nor does it currently support functions that would be necessary for things like text editors; all of this will be added back later. + * libui also now uses my [utf library](https://github.com/andlabs/utf) for UTF-8 and UTF-16 processing, to allow consistent behavior across platforms. This usage is not completely propagated throughout libui, but the Windows port uses it in most places now, and eventually this will become what libui will use throughout. + * Also introduced a formal set of contribution guidelines, see `CONTRIBUTING.md` for details. They are still WIP. + +* **17 February 2018** + * The longstanding Enter+Escape crashes on Windows have finally been fixed (thanks to @lxn). + * **Alpha 3.5 is now here.** This is a quickie release primiarly intended to deploy the above fix to package ui itself. **It is a partial binary release; sorry!** More new things will come in the next release, which will also introduce semver (so it will be called v0.4.0 instead). + * Alpha 3.5 also includes a new control gallery example. The screenshots below have not been updated yet. + +*Old announcements can be found in the NEWS.md file.* + +## Runtime Requirements + +* Windows: Windows Vista SP2 with Platform Update or newer +* Unix: GTK+ 3.10 or newer +* Mac OS X: OS X 10.8 or newer + +## Build Requirements + +* All platforms: + * [Meson](https://mesonbuild.com/) 0.48.0 or newer + * Any of Meson's backends; this section assumes you are using [Ninja](https://ninja-build.org/), but there is no reason the other backends shouldn't work. +* Windows: either + * Microsoft Visual Studio 2013 or newer (2013 is needed for `va_copy()`) — you can build either a static or a shared library + * MinGW-w64 (other flavors of MinGW may not work) — **you can only build a static library**; shared library support will be re-added once the following features come in: + * [Isolation awareness](https://msdn.microsoft.com/en-us/library/aa375197%28v=vs.85%29.aspx), which is how you get themed controls from a DLL without needing a manifest +* Unix: nothing else specific +* Mac OS X: nothing else specific, so long as you can build Cocoa programs + +## Building + +libui uses only [the standard Meson build options](https://mesonbuild.com/Builtin-options.html), so a libui build can be set up just like any other: + +``` +$ # you must be in the top-level libui directory, otherwise this won't work +$ meson setup build [options] +$ ninja -C build +``` + +Once this completes, everything will be under `build/meson-out/`. (Note that unlike the previous build processes, everything is built by default, including tests and examples.) + +The most important options are: + +* `--buildtype=(debug|release|...)` controls the type of build made; the default is `debug`. For a full list of valid values, consult [the Meson documentation](https://mesonbuild.com/Running-Meson.html). +* `--default-library=(shared|static)` controls whether libui is built as a shared library or a static library; the default is `shared`. You currently cannot specify `both`, as the build process changes depending on the target type (though I am willing to look into changing things if at all possible). +* `-Db_sanitize=which` allows enabling the chosen [sanitizer](https://github.com/google/sanitizers) on a system that supports sanitizers. The list of supported values is in [the Meson documentation](https://mesonbuild.com/Builtin-options.html#base-options). +* `--backend=backend` allows using the specified `backend` for builds instead of `ninja` (the default). A list of supported values is in [the Meson documentation](https://mesonbuild.com/Builtin-options.html#universal-options). + +Most other built-in options will work, though keep in mind there are a handful of options that cannot be overridden because libui depends on them holding a specific value; if you do override these, though, libui will warn you when you run `meson`. + +The Meson website and documentation has more in-depth usage instructions. + +For the sake of completeness, I should note that the default value of `--layout` is `flat`, not the usual `mirror`. This is done both to make creating the release archives easier as well as to reduce the chance that shared library builds will fail to start on Windows because the DLL is in another directory. You can always specify this manually if you want. + +Backends other than `ninja` should work, but are untested by me. + +## Installation + +Meson also supports installing from source; if you use Ninja, just do + +``` +$ ninja -C build install +``` + +When running `meson`, the `--prefix` option will set the installation prefix. [The Meson documentation](https://mesonbuild.com/Builtin-options.html#universal-options) has more information, and even lists more fine-grained options that you can use to control the installation. + +#### Arch Linux + +Can be built from AUR: https://aur.archlinux.org/packages/libui-git/ + +## Documentation + +Needs to be written. Consult `ui.h` and the examples for details for now. + +## Language Bindings + +libui was originally written as part of my [package ui for Go](https://github.com/andlabs/ui). Now that libui is separate, package ui has become a binding to libui. As such, package ui is the only official binding. + +Other people have made bindings to other languages: + +Language | Bindings +--- | --- +C++ | [libui-cpp](https://github.com/billyquith/libui-cpp), [cpp-libui-qtlike](https://github.com/aoloe/cpp-libui-qtlike) +C# / .NET Framework | [LibUI.Binding](https://github.com/NattyNarwhal/LibUI.Binding) +C# / .NET Core | [DevZH.UI](https://github.com/noliar/DevZH.UI), [SharpUI](https://github.com/benpye/sharpui/), [TCD.UI](https://github.com/tacdevel/tcdfx) +CHICKEN Scheme | [wasamasa/libui](https://github.com/wasamasa/libui) +Common Lisp | [jinwoo/cl-ui](https://github.com/jinwoo/cl-ui) +Crystal | [libui.cr](https://github.com/Fusion/libui.cr), [hedron](https://github.com/Qwerp-Derp/hedron) +D | [DerelictLibui (flat API)](https://github.com/Extrawurst/DerelictLibui), [libuid (object-oriented)](https://github.com/mogud/libuid) +Euphoria | [libui-euphoria](https://github.com/ghaberek/libui-euphoria) +Harbour | [hbui](https://github.com/rjopek/hbui) +Haskell | [haskell-libui](https://github.com/beijaflor-io/haskell-libui) +JavaScript/Node.js | [libui-node](https://github.com/parro-it/libui-node), [libui.js (merged into libui-node?)](https://github.com/mavenave/libui.js), [proton-native](https://github.com/kusti8/proton-native), [vuido](https://github.com/mimecorg/vuido) +Julia | [Libui.jl](https://github.com/joa-quim/Libui.jl) +Kotlin | [kotlin-libui](https://github.com/msink/kotlin-libui) +Lua | [libuilua](https://github.com/zevv/libuilua), [libui-lua](https://github.com/mdombroski/libui-lua), [lui](http://tset.de/lui/index.html), [lui](https://github.com/zhaozg/lui) +Nim | [ui](https://github.com/nim-lang/ui) +Perl6 | [perl6-libui](https://github.com/Garland-g/perl6-libui) +PHP | [ui](https://github.com/krakjoe/ui) +Python | [pylibui](https://github.com/joaoventura/pylibui) +Ruby | [libui-ruby](https://github.com/jamescook/libui-ruby), [libui](https://github.com/kojix2/libui) +Rust | [libui-rs](https://github.com/rust-native-ui/libui-rs) +Scala | [scalaui](https://github.com/lolgab/scalaui) +Swift | [libui-swift](https://github.com/sclukey/libui-swift) + +## Frequently Asked Questions + +### Why does my program start in the background on OS X if I run from the command line? +OS X normally does not start program executables directly; instead, it uses [Launch Services](https://developer.apple.com/reference/coreservices/1658613-launch_services?language=objc) to coordinate the launching of the program between the various parts of the system and the loading of info from an .app bundle. One of these coordination tasks is responsible for bringing a newly launched app into the foreground. This is called "activation". + +When you run a binary directly from the Terminal, however, you are running it directly, not through Launch Services. Therefore, the program starts in the background, because no one told it to activate! Now, it turns out [there is an API](https://developer.apple.com/reference/appkit/nsapplication/1428468-activateignoringotherapps) that we can use to force our app to be activated. But if we use it, then we'd be trampling over Launch Services, which already knows whether it should activate or not. Therefore, libui does not step over Launch Services, at the cost of requiring an extra user step if running directly from the command line. + +See also [this](https://github.com/andlabs/libui/pull/20#issuecomment-211381971) and [this](http://stackoverflow.com/questions/25318524/what-exactly-should-i-pass-to-nsapp-activateignoringotherapps-to-get-my-appl). + +## Contributing + +See `CONTRIBUTING.md`. + +## Screenshots + +From examples/controlgallery: + +![Windows](examples/controlgallery/windows.png) + +![Unix](examples/controlgallery/unix.png) + +![OS X](examples/controlgallery/darwin.png) diff --git a/dep/libui/TODO.md b/dep/libui/TODO.md new file mode 100644 index 0000000..528a658 --- /dev/null +++ b/dep/libui/TODO.md @@ -0,0 +1,262 @@ +- make sure the last line of text layouts include leading + +- documentation notes: + - static binaries do not link system libraries, meaning apps still depend on shared GTK+, etc. + - ui*Buttons are NOT compatible with uiButton functions + +- more robust layout handling + - uiFormTie() for ensuring multiple uiForms have the same label area widths + - uiSizeGroup for size groups (GtkSizeGroup on GTK+, auto layout constraints on OS X; consider adding after 10.8 is gone) + +- windows: should the initial hwndInsertAfter be HWND_BOTTOM for what we want? + +- windows: document the rules for controls and containers + +- windows: document the minimum size change propagation system + +- provisions for controls that cannot be grown? especiailly for windows + +- LC_VERSION_MIN_MACOSX has the 10.11 SDK; see if we can knock it down to 10.8 too; OS version is fine + - apply the OS version stuff to the test program and examples too + - what about micro versions (10.8.x)? force 10.8.0? + +- go through ALL the objective-c objects we create and make sure we are using the proper ownership (alloc/init and new are owned by us, all class method constructors are autoreleased - thanks mikeash) + +- on OS X, edit shortcuts like command-C working require that the menu entries be defined, or so it seems, even for NSAlert + - other platforms? + +- make sure all OS X event handlers that use target-action set the action to NULL when the target is unset + +- provide a way to get the currently selected uiTab page? set? + +- make it so that the windows cntrols only register a resize if their new minimum size is larger than their current size to easen the effect of flicker + - it won't remove that outright, but it'll help + +- add an option to the test program to run page7b as an independent test in its own window + - same for page7c + +- http://blogs.msdn.com/b/oldnewthing/archive/2004/01/12/57833.aspx provide a DEF file on Windows + +- all ports: update state when adding a control to a parent +- should uiWindowsSizing be computed against the window handle, not the parent? + +- DPI awareness on windows + +- http://stackoverflow.com/questions/4543087/applicationwillterminate-and-the-dock-but-wanting-to-cancel-this-action + +ultimately: +- MAYBE readd lifetime handling/destruction blocking +- related? [12:25] And the blue outline on those buttons [ALL clicked buttons on Windows 7] won't go away + - I get this too + - not anymore +- SWP_NOCOPYBITS to avoid button redraw issues on Windows when not in tab, but only when making resize faster +- secondary side alignment control in uiBox +- Windows: don't abort if a cleanup function fails? + +- 32-bit Mac OS X support (requires lots of code changes) + - change the build system to be more receptive to arch changes + +notes to self +- explicitly document label position at top-left corner +- explicitly document that if number of radio buttons >= 1 there will always be a selection +- mark that uiControlShow() on a uiWindow() will bring to front and give keyboard focus because of OS X + - make sure ShowWindow() is sufficient for zorder on Windows +- document that you CAN use InsertAt functions to insert at the first invalid index, even if the array is empty +- note that uiTabInsertAt() does NOT change the current tab page (it may change its index if inserting before the current page) +- note that the default action for uiWindowOnClosing() is to return 0 (keep the window open) +- note that uiInitOptions should be initialized to zero +- explicitly document that uiCheckboxSetChecked() and uiEntrySetText() do not fire uiCheckboxOnToggled() and uiEntryOnChanged(), respectively +- note that if a menu is requested on systems with menubars on windows but no menus are defined, the result is a blank menubar, with whatever that means left up to the OS to decide +- note that handling of multiple consecutive separators in menus, leading separators in menus, and trailing separators in menus are all OS-defined +- note that uiDrawMatrixInvert() does not change the matrix if it fails +- note that the use of strings that are not strictly valid UTF-8 results in undefined behavior + +- test RTL + - automate RTL +- now that stock items are deprecated, I have to maintain translations of the Cancel, Open, and Save buttons on GTK+ myself (thanks baedert in irc.gimp.net/#gtk+) + - either that or keep using stock items + +- http://blogs.msdn.com/b/oldnewthing/archive/2014/02/26/10503148.aspx + +- build optimizations + +- use http://www.appveyor.com/ to do Windows build CI since people want CI + + + + + + +- consider just having the windows backend in C++ + - consider having it all in C++ + + + +don't forget LONGTERMs as well + +notes +- http://blogs.msdn.com/b/oldnewthing/archive/2004/03/29/101121.aspx on accelerators + +- group and tab should act as if they have no child if the child is hidden +on windows + + + +- a way to do recursive main loops + - how do we handle 0 returns from non-recursive uiMainStep() calls that aren't the main loop? (event handlers, for instance) +- should repeated calls to uiMainStep() after uiQuit() return 0 reliably? this will be needed for non-recursive loops + +http://stackoverflow.com/questions/38338426/meaning-of-ampersand-in-rc-files/38338841?noredirect=1#comment64093084_38338841 + +label shortcut keys + +- remove whining from source code + +[01:41:47] Hi. does pango support "fgalpha". I see that foreground="112233xx" works ( alpha=xx ), but fgalpha is a no-op +[01:52:29] pango_attr_foreground_alpha_new (32767) seems to be called in either case, but only the "foreground" attr works +[01:56:09] lolek (lolek@ip-91-244-230-76.simant.pl) joined the channel +[01:57:48] ok. seems like "foreground" is mandatory attr, 1. "foreground-without-alpha" + "alpha" works 2. "foreground-with-alpha" works. 3. "alpha" alone doesn +[01:57:52] 't work +[01:58:29] Is there a way to just specify alpha on the current foreground color ? +[02:00:23] lolek (lolek@ip-91-244-230-76.simant.pl) left the channel +[02:07:41] mjog (mjog@uniwide-pat-pool-129-94-8-98.gw.unsw.edu.au) left IRC (Quit: mjog) +[02:08:10] seb128 (seb128@53542B83.cm-6-5a.dynamic.ziggo.nl) joined the channel +[02:12:37] huh +[02:12:41] what version of pango? +[02:13:05] the latest . +[02:15:00] 1.40.3 +[02:20:46] I'll ahve to keep this in mind then, thanks +[02:20:59] if only there was a cairo-specific attribute for alpha... + +FONT LOADING + +[00:10:08] andlabs: is there API yet to load from memory? last i checked i only found from file (which we use in builder). https://git.gnome.org/browse/gnome-builder/tree/libide/editor/ide-editor-map-bin.c#n115 +[00:13:12] mrmcq2u_ (mrmcq2u@109.79.53.90) joined the channel +[00:14:59] mrmcq2u (mrmcq2u@109.79.73.102) left IRC (Ping timeout: 181 seconds) +[00:15:19] hergertme: no, which is why I was asking =P +[00:15:30] I would have dug down if I could ensure at least something about the backends a GTK+ 3 program uses +[00:15:39] on all platforms except windows and os x +[00:16:11] to the best of my (partially outdated, given pace of foss) knowledge there isn't an api to load from memory +[00:16:28] you can possibly make a tmpdir and put a temp file in there +[00:16:52] and load that as your font dir in your FcConfig, so any PangoFontDescription would point to that one font, no matter what +[00:17:18] (using the API layed out in that link) +[00:18:18] dsr1014__ (dsr1014@c-73-72-102-18.hsd1.il.comcast.net) joined the channel +[00:35:18] simukis_ (simukis@78-60-58-6.static.zebra.lt) left IRC (Quit: simukis_) +[00:35:48] dreamon_ (dreamon@ppp-188-174-49-41.dynamic.mnet-online.de) joined the channel +[00:40:09] samtoday_ (samtoday@114-198-116-132.dyn.iinet.net.au) joined the channel +[00:40:32] mjog (mjog@120.18.225.46) joined the channel +[00:40:38] hergertme: not necessarily fontconfig +[00:40:45] it can be with ft2 or xft I guess +[00:40:55] especially since I want the API NOT to make the font part of the font panel +[00:42:07] what sort of deprecated code are you trying to support? +[00:42:35] both of those are deprecated in pango fwiw +[00:43:06] on Linux im pretty sure we use FC everywhere these days +[00:44:46] (and gtk_widget_set_font_map() is how you get your custom font into a widget without affecting the global font lists, as layed out in that link) +[00:49:14] vasaikar (vasaikar@125.16.97.121) joined the channel +[00:50:14] karlt (karl@2400:e780:801:224:f121:e611:d139:e70e) left IRC (Client exited) +[00:50:49] karlt (karl@2400:e780:801:224:f121:e611:d139:e70e) joined the channel +[00:51:43] PioneerAxon (PioneerAxo@122.171.61.146) left IRC (Ping timeout: 180 seconds) +[00:57:47] PioneerAxon (PioneerAxo@106.201.37.181) joined the channel +[01:03:01] karlt (karl@2400:e780:801:224:f121:e611:d139:e70e) left IRC (Ping timeout: 181 seconds) +[01:05:49] muhannad (muhannad@95.218.26.152) left IRC (Quit: muhannad) +[01:07:51] hergertme: hm +[01:07:54] all right, thanks +[01:08:05] hergertme: fwiw right now my requirement is 3.10 +[01:10:47] ah, well you'll probably be missing the neccesary font API on gtk_widget +[01:11:04] but pango should be fine even back as far as https://developer.gnome.org/pango/1.28/PangoFcFontMap.html +[01:11:56] good +[01:12:04] because this is for custom drawing into a DrawingArea +[01:14:12] presumably just create your PangoContext as normal, but call pango_context_set_font_map() with the map you've setup. now, the load a font from a file i dont think was added to FontConfig until later though (not sure what release) +[01:15:53] FcConfigAppFontAddFile() <-- that API +[01:16:30] great, and they don't say what version the API was added in teh docs +function: ide_editor_map_bin_add() + +- Mouse ClickLock: do we need to do anything special? *should* we? https://msdn.microsoft.com/en-us/library/windows/desktop/ms724947(v=vs.85).aspx +- consider a uiAnticipateDoubleClick() or uiDoubleClickTime() (for a uiQueueTimer()) or something: https://blogs.msdn.microsoft.com/oldnewthing/20041015-00/?p=37553 + +- determine whether MSGF_USER is for and if it's correct for our uiArea message filter (if we have one) + +- source file encoding and MSVC compiler itself? https://stackoverflow.com/questions/20518040/how-can-i-get-the-directwrite-padwrite-sample-to-work + - also need to worry about object file and output encoding... + - this also names the author of the padwrite sample + +- OpenType features TODOs + - https://stackoverflow.com/questions/32545675/what-are-the-default-typography-settings-used-by-idwritetextlayout + - feature/shaping interaction rules for arabic: https://www.microsoft.com/typography/OpenTypeDev/arabic/intro.htm + - other stuff, mostly about UIs and what users expect to be able to set + - https://klim.co.nz/blog/towards-an-ideal-opentype-user-interface/ + - https://libregraphicsmeeting.org/2016/designing-for-many-applications-opentype-features-ui/ + - https://www.youtube.com/watch?v=wEyDhsH076Y + - https://twitter.com/peter_works + - http://ilovetypography.com/2014/10/22/better-ui-for-better-typography-adobe-petition/ + - http://silgraphite.sourceforge.net/ui/studynote.html + +- add NXCOMPAT (DEP awareness) to the Windows builds + - and ASLR too? or is that not a linker setting + +OS X: embedding an Info.plist into a binary directly +https://www.objc.io/issues/6-build-tools/mach-o-executables/ +TODO will this let Dictation work? +TODO investigate ad-hoc codesigning + +https://blogs.msdn.microsoft.com/oldnewthing/20040112-00/?p=41083 def files for decoration (I forget if I said this earlier) + +TODO ClipCursor() stuff; probably not useful for libui but still +https://blogs.msdn.microsoft.com/oldnewthing/20140102-00/?p=2183 +https://blogs.msdn.microsoft.com/oldnewthing/20061117-03/?p=28973 +https://msdn.microsoft.com/en-us/library/windows/desktop/ms648383(v=vs.85).aspx + +https://cmake.org/Wiki/CMake_Useful_Variables +set(CMAKE_SHARED_LINKER_FLAGS "-Wl,--no-undefined") +On Unix systems, this will make linker report any unresolved symbols from object files (which is quite typical when you compile many targets in CMake projects, but do not bother with linking target dependencies in proper order). +(I used to have something like this back when I used makefiles; did it convert in? I forget) + +look into these for the os x port +https://developer.apple.com/documentation/appkit/view_management/nseditor?language=objc +https://developer.apple.com/documentation/appkit/view_management/nseditorregistration?language=objc + +for future versions of the os x port +https://developer.apple.com/documentation/appkit/nslayoutguide?language=objc and anchors +https://developer.apple.com/documentation/appkit/nsuserinterfacecompression?language=objc https://developer.apple.com/documentation/appkit/nsuserinterfacecompressionoptions?language=objc +though at some point we'll be able to use NSStackView and NSGridView directly, so... + +Cocoa PDFs +https://developer.apple.com/documentation/appkit/nspdfimagerep?language=objc +https://developer.apple.com/documentation/coregraphics?language=objc +https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Printing/osxp_pagination/osxp_pagination.html#//apple_ref/doc/uid/20001051-119037 +https://developer.apple.com/documentation/appkit/nsprintoperation/1529269-pdfoperationwithview?language=objc +https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Printing/osxp_printapps/osxp_printapps.html#//apple_ref/doc/uid/20000861-BAJBFGED +https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Printing/osxp_printingapi/osxp_printingapi.html#//apple_ref/doc/uid/10000083i-CH2-SW2 +https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Printing/osxp_printinfo/osxp_printinfo.html#//apple_ref/doc/uid/20000864-BAJBFGED +https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Printing/osxp_printlayoutpanel/osxp_printlayoutpanel.html#//apple_ref/doc/uid/20000863-BAJBFGED +https://developer.apple.com/documentation/appkit/nspagelayout?language=objc +https://developer.apple.com/documentation/appkit/nsprintinfo?language=objc +https://developer.apple.com/documentation/applicationservices/core_printing?language=objc +https://developer.apple.com/documentation/applicationservices/1463247-pmcreatesession?language=objc +https://developer.apple.com/documentation/applicationservices/pmprintsession?language=objc +https://developer.apple.com/documentation/applicationservices/1460101-pmsessionbegincgdocumentnodialog?language=objc +https://developer.apple.com/documentation/applicationservices/1463416-pmsessionbeginpagenodialog?language=objc +https://developer.apple.com/documentation/applicationservices/1506831-anonymous/kpmdestinationprocesspdf?language=objc +https://developer.apple.com/documentation/applicationservices/1461960-pmcreategenericprinter?language=objc +https://developer.apple.com/documentation/applicationservices/1460101-pmsessionbegincgdocumentnodialog?language=objc +https://developer.apple.com/documentation/applicationservices/1464527-pmsessionenddocumentnodialog?language=objc +https://developer.apple.com/documentation/applicationservices/1461952-pmsessiongetcggraphicscontext?language=objc +https://developer.apple.com/library/content/technotes/tn2248/_index.html +https://developer.apple.com/library/content/samplecode/PMPrinterPrintWithFile/Introduction/Intro.html +https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Printing/osxp_aboutprinting/osxp_aboutprt.html + +- run os x code with `OBJC_DEBUG_MISSING_POOLS=YES` and other `OBJC_HELP=YES` options + - turn off the autorelease pool to make sure we're not autoreleasing improperly + +TODO investigate -Weverything in clang alongside -Wall in MSVC (and in gcc too maybe...) + +mac os x accessibility +- https://developer.apple.com/documentation/appkit/nsworkspace/1524656-accessibilitydisplayshoulddiffer?language=objc +- https://developer.apple.com/documentation/appkit/nsworkspace/1526290-accessibilitydisplayshouldincrea?language=objc +- https://developer.apple.com/documentation/appkit/nsworkspace/1533006-accessibilitydisplayshouldreduce?language=objc + +uiEntry disabling bugs http://www.cocoabuilder.com/archive/cocoa/215525-nstextfield-bug-can-be.html +uiMultilineEntry disabling https://developer.apple.com/library/content/qa/qa1461/_index.html + +more TODOs: +- make no guarantee about buildability of feature branches diff --git a/dep/libui/UPSTREAM.md b/dep/libui/UPSTREAM.md new file mode 100644 index 0000000..a5c8f4d --- /dev/null +++ b/dep/libui/UPSTREAM.md @@ -0,0 +1,3 @@ +This is a clone of the master branch of https://github.com/andlabs/libui made +on 2021-12-05. + diff --git a/dep/libui/azure-pipelines.yml b/dep/libui/azure-pipelines.yml new file mode 100644 index 0000000..a7eb474 --- /dev/null +++ b/dep/libui/azure-pipelines.yml @@ -0,0 +1,378 @@ +# 31 march 2019 + +trigger: + branches: + include: + - '*' + tags: + include: + - '*' + +variables: + releaseExamples: 'controlgallery cpp-multithread datetime drawtext histogram tester timer' + +jobs: + +# linux { + +- job: linux_386_shared + displayName: 'Linux 386 Shared' + pool: + vmImage: 'ubuntu-16.04' + workspace: + clean: all + steps: + - template: azure-pipelines/setup-python3.yml + - template: azure-pipelines/install-latest-meson-ninja.yml + - template: azure-pipelines/linux-386-install-gtk-dev.yml + - template: azure-pipelines/configure.yml + parameters: + beforeConfigure: export CFLAGS=-m32 CXXFLAGS=-m32 PKG_CONFIG_PATH=/usr/lib/i386-linux-gnu/pkgconfig + defaultLibrary: shared + - template: azure-pipelines/build.yml + - template: azure-pipelines/artifacts.yml + parameters: + os: linux + arch: 386 + libtype: shared + libfiles: libui.so.0 + osHeader: ui_unix.h + +- job: linux_386_static + displayName: 'Linux 386 Static' + pool: + vmImage: 'ubuntu-16.04' + workspace: + clean: all + steps: + - template: azure-pipelines/setup-python3.yml + - template: azure-pipelines/install-latest-meson-ninja.yml + - template: azure-pipelines/linux-386-install-gtk-dev.yml + - template: azure-pipelines/configure.yml + parameters: + beforeConfigure: export CFLAGS=-m32 CXXFLAGS=-m32 PKG_CONFIG_PATH=/usr/lib/i386-linux-gnu/pkgconfig + defaultLibrary: static + - template: azure-pipelines/build.yml + - template: azure-pipelines/artifacts.yml + parameters: + os: linux + arch: 386 + libtype: static + libfiles: libui.a + osHeader: ui_unix.h + +- job: linux_amd64_shared + displayName: 'Linux amd64 Shared' + pool: + vmImage: 'ubuntu-16.04' + workspace: + clean: all + steps: + - template: azure-pipelines/setup-python3.yml + - template: azure-pipelines/install-latest-meson-ninja.yml + - template: azure-pipelines/linux-install-gtk-dev.yml + - template: azure-pipelines/configure.yml + parameters: + defaultLibrary: shared + - template: azure-pipelines/build.yml + - template: azure-pipelines/artifacts.yml + parameters: + os: linux + arch: amd64 + libtype: shared + libfiles: libui.so.0 + osHeader: ui_unix.h + +- job: linux_amd64_static + displayName: 'Linux amd64 Static' + pool: + vmImage: 'ubuntu-16.04' + workspace: + clean: all + steps: + - template: azure-pipelines/setup-python3.yml + - template: azure-pipelines/install-latest-meson-ninja.yml + - template: azure-pipelines/linux-install-gtk-dev.yml + - template: azure-pipelines/configure.yml + parameters: + defaultLibrary: static + - template: azure-pipelines/build.yml + - template: azure-pipelines/artifacts.yml + parameters: + os: linux + arch: amd64 + libtype: static + libfiles: libui.a + osHeader: ui_unix.h + +# } + +# windows vs2015 { + +- job: windows_386_msvc2015_shared + displayName: 'Windows 386 MSVC2015 Shared' + pool: + vmImage: 'vs2015-win2012r2' + workspace: + clean: all + steps: + - template: azure-pipelines/vs2015-install-python3.yml + - template: azure-pipelines/install-latest-meson-ninja.yml + - template: azure-pipelines/windows-install-ninja.yml + - template: azure-pipelines/configure.yml + parameters: + beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86 + defaultLibrary: shared + - template: azure-pipelines/build.yml + parameters: + beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86 + - template: azure-pipelines/windows-artifacts.yml + parameters: + os: windows + arch: 386 + toolchain: msvc2015 + libtype: shared + libfiles: libui.dll libui.exp libui.lib + osHeader: ui_windows.h + +- job: windows_386_msvc2015_static + displayName: 'Windows 386 MSVC2015 Static' + pool: + vmImage: 'vs2015-win2012r2' + workspace: + clean: all + steps: + - template: azure-pipelines/vs2015-install-python3.yml + - template: azure-pipelines/install-latest-meson-ninja.yml + - template: azure-pipelines/windows-install-ninja.yml + - template: azure-pipelines/configure.yml + parameters: + beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86 + defaultLibrary: static + - template: azure-pipelines/build.yml + parameters: + beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86 + afterBuild: ren build\meson-out\libui.a libui.lib + - template: azure-pipelines/windows-artifacts.yml + parameters: + os: windows + arch: 386 + toolchain: msvc2015 + libtype: static + libfiles: libui.lib + osHeader: ui_windows.h + +- job: windows_amd64_msvc2015_shared + displayName: 'Windows amd64 MSVC2015 Shared' + pool: + vmImage: 'vs2015-win2012r2' + workspace: + clean: all + steps: + - template: azure-pipelines/vs2015-install-python3.yml + - template: azure-pipelines/install-latest-meson-ninja.yml + - template: azure-pipelines/windows-install-ninja.yml + - template: azure-pipelines/configure.yml + parameters: + beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" amd64 + defaultLibrary: shared + - template: azure-pipelines/build.yml + parameters: + beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" amd64 + - template: azure-pipelines/windows-artifacts.yml + parameters: + os: windows + arch: amd64 + toolchain: msvc2015 + libtype: shared + libfiles: libui.dll libui.exp libui.lib + osHeader: ui_windows.h + +- job: windows_amd64_msvc2015_static + displayName: 'Windows amd64 MSVC2015 Static' + pool: + vmImage: 'vs2015-win2012r2' + workspace: + clean: all + steps: + - template: azure-pipelines/vs2015-install-python3.yml + - template: azure-pipelines/install-latest-meson-ninja.yml + - template: azure-pipelines/windows-install-ninja.yml + - template: azure-pipelines/configure.yml + parameters: + beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" amd64 + defaultLibrary: static + - template: azure-pipelines/build.yml + parameters: + beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" amd64 + afterBuild: ren build\meson-out\libui.a libui.lib + - template: azure-pipelines/windows-artifacts.yml + parameters: + os: windows + arch: amd64 + toolchain: msvc2015 + libtype: static + libfiles: libui.lib + osHeader: ui_windows.h + +# } + +# windows vs2017 { + +- job: windows_386_msvc2017_shared + displayName: 'Windows 386 MSVC2017 Shared' + pool: + vmImage: 'vs2017-win2016' + workspace: + clean: all + steps: + - template: azure-pipelines/setup-python3.yml + - template: azure-pipelines/install-latest-meson-ninja.yml + - template: azure-pipelines/windows-install-ninja.yml + - template: azure-pipelines/configure.yml + parameters: + beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x86 + defaultLibrary: shared + - template: azure-pipelines/build.yml + parameters: + beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x86 + - template: azure-pipelines/windows-artifacts.yml + parameters: + os: windows + arch: 386 + toolchain: msvc2017 + libtype: shared + libfiles: libui.dll libui.exp libui.lib + osHeader: ui_windows.h + +- job: windows_386_msvc2017_static + displayName: 'Windows 386 MSVC2017 Static' + pool: + vmImage: 'vs2017-win2016' + workspace: + clean: all + steps: + - template: azure-pipelines/setup-python3.yml + - template: azure-pipelines/install-latest-meson-ninja.yml + - template: azure-pipelines/windows-install-ninja.yml + - template: azure-pipelines/configure.yml + parameters: + beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x86 + defaultLibrary: static + - template: azure-pipelines/build.yml + parameters: + beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x86 + afterBuild: ren build\meson-out\libui.a libui.lib + - template: azure-pipelines/windows-artifacts.yml + parameters: + os: windows + arch: 386 + toolchain: msvc2017 + libtype: static + libfiles: libui.lib + osHeader: ui_windows.h + +- job: windows_amd64_msvc2017_shared + displayName: 'Windows amd64 MSVC2017 Shared' + pool: + vmImage: 'vs2017-win2016' + workspace: + clean: all + steps: + - template: azure-pipelines/setup-python3.yml + - template: azure-pipelines/install-latest-meson-ninja.yml + - template: azure-pipelines/windows-install-ninja.yml + - template: azure-pipelines/configure.yml + parameters: + beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" amd64 + defaultLibrary: shared + - template: azure-pipelines/build.yml + parameters: + beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" amd64 + - template: azure-pipelines/windows-artifacts.yml + parameters: + os: windows + arch: amd64 + toolchain: msvc2017 + libtype: shared + libfiles: libui.dll libui.exp libui.lib + osHeader: ui_windows.h + +- job: windows_amd64_msvc2017_static + displayName: 'Windows amd64 MSVC2017 Static' + pool: + vmImage: 'vs2017-win2016' + workspace: + clean: all + steps: + - template: azure-pipelines/setup-python3.yml + - template: azure-pipelines/install-latest-meson-ninja.yml + - template: azure-pipelines/windows-install-ninja.yml + - template: azure-pipelines/configure.yml + parameters: + beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" amd64 + defaultLibrary: static + - template: azure-pipelines/build.yml + parameters: + beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" amd64 + afterBuild: ren build\meson-out\libui.a libui.lib + - template: azure-pipelines/windows-artifacts.yml + parameters: + os: windows + arch: amd64 + toolchain: msvc2017 + libtype: static + libfiles: libui.lib + osHeader: ui_windows.h + +# } + +# mac { + +# TODO beforeConfigure/beforeBuild: export SDKROOT=$(xcodebuild -version -sdk macosx10.13 Path)? + +- job: darwin_amd64_shared + displayName: 'Darwin amd64 Shared' + pool: + vmImage: 'macos-10.13' + workspace: + clean: all + steps: + - template: azure-pipelines/setup-python3.yml + - template: azure-pipelines/install-latest-meson-ninja.yml + - template: azure-pipelines/darwin-install-ninja.yml + - template: azure-pipelines/configure.yml + parameters: + defaultLibrary: shared + - template: azure-pipelines/build.yml + - template: azure-pipelines/artifacts.yml + parameters: + os: darwin + arch: amd64 + libtype: shared + libfiles: libui.A.dylib + osHeader: ui_darwin.h + +- job: darwin_amd64_static + displayName: 'Darwin amd64 Static' + pool: + vmImage: 'macos-10.13' + workspace: + clean: all + steps: + - template: azure-pipelines/setup-python3.yml + - template: azure-pipelines/install-latest-meson-ninja.yml + - template: azure-pipelines/darwin-install-ninja.yml + - template: azure-pipelines/configure.yml + parameters: + defaultLibrary: static + - template: azure-pipelines/build.yml + - template: azure-pipelines/artifacts.yml + parameters: + os: darwin + arch: amd64 + libtype: static + libfiles: libui.a + osHeader: ui_darwin.h + +# } diff --git a/dep/libui/azure-pipelines/TODOMatrix b/dep/libui/azure-pipelines/TODOMatrix new file mode 100644 index 0000000..516eb4e --- /dev/null +++ b/dep/libui/azure-pipelines/TODOMatrix @@ -0,0 +1,399 @@ +# 31 march 2019 + +variables: + releaseExamples: 'controlgallery cpp-multithread datetime drawtext histogram tester timer' + +strategy: + matrix: +# targetname: +# os: 'fill this in' +# arch: 'fill this in' +# toolchain: 'fill this in' +# libtype: 'fill this in' +# vmImage: 'fill this in' +# python3Template: 'fill filename' +# depsAndNinjaTemplate: 'fill filename' +# beforeConfigure: 'fill this in' +# beforeBuild: 'fill this in' +# afterBuild: 'fill this in' +# artifactTemplate: 'fill filename' +# libfiles: 'fill this in' +# osHeader: 'fill this in' + linux_386_shared: + os: 'linux' + arch: '386' + libtype: 'shared' + vmImage: 'ubuntu-16.04' + python3Template: 'azure-pipelines/setup-python3.yml' + depsAndNinjaTemplate: 'azure-pipelines/linux-386-install-gtk-dev.yml' + beforeConfigure: 'export CFLAGS=-m32 CXXFLAGS=-m32 PKG_CONFIG_PATH=/usr/lib/i386-linux-gnu/pkgconfig' + artifactTemplate: 'azure-pipelines/artifacts.yml' + libfiles: 'libui.so.0' + osHeader: 'ui_unix.h' + +pool: + vmImage: $(vmImage) + +workspace: + clean: all + +steps: +- template: $(variables.python3Template) +- template: azure-pipelines/install-latest-meson-ninja.yml +- template: $(variables.depsAndNinjaTemplate) +- template: azure-pipelines/configure.yml + parameters: + beforeConfigure: $(beforeConfigure) + defaultLibrary: $(libtype) +- template: azure-pipelines/build.yml + parameters: + beforeBuild: $(beforeBuild) + afterBuild: $(afterBuild) +- template: $(variables.artifactTemplate) + parameters: + os: $(os) + arch: $(arch) + toolchain: $(toolchain) + libtype: $(libtype) + libfiles: $(libfiles) + osHeader: $(osHeader) + +## linux { +#- job: linux_386_static +# displayName: 'Linux 386 Static' +# pool: +# vmImage: 'ubuntu-16.04' +# workspace: +# clean: all +# steps: +# - template: azure-pipelines/setup-python3.yml +# - template: azure-pipelines/install-latest-meson-ninja.yml +# - template: azure-pipelines/linux-386-install-gtk-dev.yml +# - template: azure-pipelines/configure.yml +# parameters: +# beforeConfigure: export CFLAGS=-m32 CXXFLAGS=-m32 PKG_CONFIG_PATH=/usr/lib/i386-linux-gnu/pkgconfig +# defaultLibrary: static +# - template: azure-pipelines/build.yml +# - template: azure-pipelines/artifacts.yml +# parameters: +# os: linux +# arch: 386 +# libtype: static +# libfiles: libui.a +# osHeader: ui_unix.h +# +#- job: linux_amd64_shared +# displayName: 'Linux amd64 Shared' +# pool: +# vmImage: 'ubuntu-16.04' +# workspace: +# clean: all +# steps: +# - template: azure-pipelines/setup-python3.yml +# - template: azure-pipelines/install-latest-meson-ninja.yml +# - template: azure-pipelines/linux-install-gtk-dev.yml +# - template: azure-pipelines/configure.yml +# parameters: +# defaultLibrary: shared +# - template: azure-pipelines/build.yml +# - template: azure-pipelines/artifacts.yml +# parameters: +# os: linux +# arch: amd64 +# libtype: shared +# libfiles: libui.so.0 +# osHeader: ui_unix.h +# +#- job: linux_amd64_static +# displayName: 'Linux amd64 Static' +# pool: +# vmImage: 'ubuntu-16.04' +# workspace: +# clean: all +# steps: +# - template: azure-pipelines/setup-python3.yml +# - template: azure-pipelines/install-latest-meson-ninja.yml +# - template: azure-pipelines/linux-install-gtk-dev.yml +# - template: azure-pipelines/configure.yml +# parameters: +# defaultLibrary: static +# - template: azure-pipelines/build.yml +# - template: azure-pipelines/artifacts.yml +# parameters: +# os: linux +# arch: amd64 +# libtype: static +# libfiles: libui.a +# osHeader: ui_unix.h +# +## } +# +## windows vs2015 { +# +#- job: windows_386_msvc2015_shared +# displayName: 'Windows 386 MSVC2015 Shared' +# pool: +# vmImage: 'vs2015-win2012r2' +# workspace: +# clean: all +# steps: +# - template: azure-pipelines/vs2015-install-python3.yml +# - template: azure-pipelines/install-latest-meson-ninja.yml +# - template: azure-pipelines/windows-install-ninja.yml +# - template: azure-pipelines/configure.yml +# parameters: +# beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86 +# defaultLibrary: shared +# - template: azure-pipelines/build.yml +# parameters: +# beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86 +# - template: azure-pipelines/windows-artifacts.yml +# parameters: +# os: windows +# arch: 386 +# toolchain: msvc2015 +# libtype: shared +# libfiles: libui.dll libui.exp libui.lib +# osHeader: ui_windows.h +# +#- job: windows_386_msvc2015_static +# displayName: 'Windows 386 MSVC2015 Static' +# pool: +# vmImage: 'vs2015-win2012r2' +# workspace: +# clean: all +# steps: +# - template: azure-pipelines/vs2015-install-python3.yml +# - template: azure-pipelines/install-latest-meson-ninja.yml +# - template: azure-pipelines/windows-install-ninja.yml +# - template: azure-pipelines/configure.yml +# parameters: +# beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86 +# defaultLibrary: static +# - template: azure-pipelines/build.yml +# parameters: +# beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86 +# afterBuild: ren build\meson-out\libui.a libui.lib +# - template: azure-pipelines/windows-artifacts.yml +# parameters: +# os: windows +# arch: 386 +# toolchain: msvc2015 +# libtype: static +# libfiles: libui.lib +# osHeader: ui_windows.h +# +#- job: windows_amd64_msvc2015_shared +# displayName: 'Windows amd64 MSVC2015 Shared' +# pool: +# vmImage: 'vs2015-win2012r2' +# workspace: +# clean: all +# steps: +# - template: azure-pipelines/vs2015-install-python3.yml +# - template: azure-pipelines/install-latest-meson-ninja.yml +# - template: azure-pipelines/windows-install-ninja.yml +# - template: azure-pipelines/configure.yml +# parameters: +# beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" amd64 +# defaultLibrary: shared +# - template: azure-pipelines/build.yml +# parameters: +# beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" amd64 +# - template: azure-pipelines/windows-artifacts.yml +# parameters: +# os: windows +# arch: amd64 +# toolchain: msvc2015 +# libtype: shared +# libfiles: libui.dll libui.exp libui.lib +# osHeader: ui_windows.h +# +#- job: windows_amd64_msvc2015_static +# displayName: 'Windows amd64 MSVC2015 Static' +# pool: +# vmImage: 'vs2015-win2012r2' +# workspace: +# clean: all +# steps: +# - template: azure-pipelines/vs2015-install-python3.yml +# - template: azure-pipelines/install-latest-meson-ninja.yml +# - template: azure-pipelines/windows-install-ninja.yml +# - template: azure-pipelines/configure.yml +# parameters: +# beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" amd64 +# defaultLibrary: static +# - template: azure-pipelines/build.yml +# parameters: +# beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" amd64 +# afterBuild: ren build\meson-out\libui.a libui.lib +# - template: azure-pipelines/windows-artifacts.yml +# parameters: +# os: windows +# arch: amd64 +# toolchain: msvc2015 +# libtype: static +# libfiles: libui.lib +# osHeader: ui_windows.h +# +## } +# +## windows vs2017 { +# +#- job: windows_386_msvc2017_shared +# displayName: 'Windows 386 MSVC2017 Shared' +# pool: +# vmImage: 'vs2017-win2016' +# workspace: +# clean: all +# steps: +# - template: azure-pipelines/setup-python3.yml +# - template: azure-pipelines/install-latest-meson-ninja.yml +# - template: azure-pipelines/windows-install-ninja.yml +# - template: azure-pipelines/configure.yml +# parameters: +# beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x86 +# defaultLibrary: shared +# - template: azure-pipelines/build.yml +# parameters: +# beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x86 +# - template: azure-pipelines/windows-artifacts.yml +# parameters: +# os: windows +# arch: 386 +# toolchain: msvc2017 +# libtype: shared +# libfiles: libui.dll libui.exp libui.lib +# osHeader: ui_windows.h +# +#- job: windows_386_msvc2017_static +# displayName: 'Windows 386 MSVC2017 Static' +# pool: +# vmImage: 'vs2017-win2016' +# workspace: +# clean: all +# steps: +# - template: azure-pipelines/setup-python3.yml +# - template: azure-pipelines/install-latest-meson-ninja.yml +# - template: azure-pipelines/windows-install-ninja.yml +# - template: azure-pipelines/configure.yml +# parameters: +# beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x86 +# defaultLibrary: static +# - template: azure-pipelines/build.yml +# parameters: +# beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x86 +# afterBuild: ren build\meson-out\libui.a libui.lib +# - template: azure-pipelines/windows-artifacts.yml +# parameters: +# os: windows +# arch: 386 +# toolchain: msvc2017 +# libtype: static +# libfiles: libui.lib +# osHeader: ui_windows.h +# +#- job: windows_amd64_msvc2017_shared +# displayName: 'Windows amd64 MSVC2017 Shared' +# pool: +# vmImage: 'vs2017-win2016' +# workspace: +# clean: all +# steps: +# - template: azure-pipelines/setup-python3.yml +# - template: azure-pipelines/install-latest-meson-ninja.yml +# - template: azure-pipelines/windows-install-ninja.yml +# - template: azure-pipelines/configure.yml +# parameters: +# beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" amd64 +# defaultLibrary: shared +# - template: azure-pipelines/build.yml +# parameters: +# beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" amd64 +# - template: azure-pipelines/windows-artifacts.yml +# parameters: +# os: windows +# arch: amd64 +# toolchain: msvc2017 +# libtype: shared +# libfiles: libui.dll libui.exp libui.lib +# osHeader: ui_windows.h +# +#- job: windows_amd64_msvc2017_static +# displayName: 'Windows amd64 MSVC2017 Static' +# pool: +# vmImage: 'vs2017-win2016' +# workspace: +# clean: all +# steps: +# - template: azure-pipelines/setup-python3.yml +# - template: azure-pipelines/install-latest-meson-ninja.yml +# - template: azure-pipelines/windows-install-ninja.yml +# - template: azure-pipelines/configure.yml +# parameters: +# beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" amd64 +# defaultLibrary: static +# - template: azure-pipelines/build.yml +# parameters: +# beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" amd64 +# afterBuild: ren build\meson-out\libui.a libui.lib +# - template: azure-pipelines/windows-artifacts.yml +# parameters: +# os: windows +# arch: amd64 +# toolchain: msvc2017 +# libtype: static +# libfiles: libui.lib +# osHeader: ui_windows.h +# +## } +# +## mac { +# +## TODO beforeConfigure/beforeBuild: export SDKROOT=$(xcodebuild -version -sdk macosx10.13 Path)? +# +#- job: darwin_amd64_shared +# displayName: 'Darwin amd64 Shared' +# pool: +# vmImage: 'macos-10.13' +# workspace: +# clean: all +# steps: +# - template: azure-pipelines/setup-python3.yml +# - template: azure-pipelines/install-latest-meson-ninja.yml +# - template: azure-pipelines/darwin-install-ninja.yml +# - template: azure-pipelines/configure.yml +# parameters: +# defaultLibrary: shared +# - template: azure-pipelines/build.yml +# - template: azure-pipelines/artifacts.yml +# parameters: +# os: darwin +# arch: amd64 +# libtype: shared +# libfiles: libui.A.dylib +# osHeader: ui_darwin.h +# +#- job: darwin_amd64_static +# displayName: 'Darwin amd64 Static' +# pool: +# vmImage: 'macos-10.13' +# workspace: +# clean: all +# steps: +# - template: azure-pipelines/setup-python3.yml +# - template: azure-pipelines/install-latest-meson-ninja.yml +# - template: azure-pipelines/darwin-install-ninja.yml +# - template: azure-pipelines/configure.yml +# parameters: +# defaultLibrary: static +# - template: azure-pipelines/build.yml +# - template: azure-pipelines/artifacts.yml +# parameters: +# os: darwin +# arch: amd64 +# libtype: static +# libfiles: libui.a +# osHeader: ui_darwin.h +# +## } diff --git a/dep/libui/azure-pipelines/artifacts.yml b/dep/libui/azure-pipelines/artifacts.yml new file mode 100644 index 0000000..cfb152e --- /dev/null +++ b/dep/libui/azure-pipelines/artifacts.yml @@ -0,0 +1,28 @@ +# 6 april 2019 + +parameters: + os: '' + arch: '' + libtype: '' + libfiles: '' + osHeader: '' + +steps: +- script: | + set -x + pushd build/meson-out + cp ../../ui.h ../../${{ parameters.osHeader }} . + tar czf $(Build.ArtifactStagingDirectory)/libui-$(Build.SourceBranchName)-${{ parameters.os }}-${{ parameters.arch }}-${{ parameters.libtype }}.tgz ${{ parameters.libfiles }} ui.h ${{ parameters.osHeader}} + tar czf $(Build.ArtifactStagingDirectory)/examples-$(Build.SourceBranchName)-${{ parameters.os }}-${{ parameters.arch }}-${{ parameters.libtype }}.tgz $(releaseExamples) + rm ui.h ${{ parameters.osHeader }} + popd + displayName: 'Create Artifacts' +- task: GitHubRelease@0 + condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/') + inputs: + gitHubConnection: andlabs + repositoryName: andlabs/libui + action: 'edit' + addChangelog: false + assets: '$(Build.ArtifactStagingDirectory)/*' + assetUploadMode: 'replace' diff --git a/dep/libui/azure-pipelines/build.yml b/dep/libui/azure-pipelines/build.yml new file mode 100644 index 0000000..e4410d6 --- /dev/null +++ b/dep/libui/azure-pipelines/build.yml @@ -0,0 +1,12 @@ +# 5 april 2019 + +parameters: + beforeBuild: '' + afterBuild: '' + +steps: +- script: | + ${{ parameters.beforeBuild }} + ninja -C build -v + ${{ parameters.afterBuild }} + displayName: 'Build' diff --git a/dep/libui/azure-pipelines/collapse.awk b/dep/libui/azure-pipelines/collapse.awk new file mode 100644 index 0000000..d10b9bb --- /dev/null +++ b/dep/libui/azure-pipelines/collapse.awk @@ -0,0 +1,43 @@ +# 7 april 2019 + +BEGIN { + RS = "" + FS = "\n +- " +} + +/^- job:/ { + for (i = 1; i <= NF; i++) { + if (!(i in nextindex)) { + # fast path for first occurrence + lines[i, 0] = $i + nextindex[i] = 1 + if (maxIndex < i) + maxIndex = i + continue + } + found = 0 + for (j = 0; j < nextindex[i]; j++) + if (lines[i, j] == $i) { + found = 1 + break + } + if (!found) { + lines[i, nextindex[i]] = $i + nextindex[i]++ + } + } +} + +END { + for (i = 1; i <= maxIndex; i++) { + if (nextindex[i] == 1) { + # only one entry here, just print it + print "- " lines[i, 0] + continue + } + print "{" + for (j = 0; j < nextindex[i]; j++) + print "- " lines[i, j] + print "}" + } +} diff --git a/dep/libui/azure-pipelines/collapsed b/dep/libui/azure-pipelines/collapsed new file mode 100644 index 0000000..20e59dc --- /dev/null +++ b/dep/libui/azure-pipelines/collapsed @@ -0,0 +1,298 @@ +{ +- - job: linux_386_shared + displayName: 'Linux 386 Shared' + pool: + vmImage: 'ubuntu-16.04' + workspace: + clean: all + steps: +- - job: linux_386_static + displayName: 'Linux 386 Static' + pool: + vmImage: 'ubuntu-16.04' + workspace: + clean: all + steps: +- - job: linux_amd64_shared + displayName: 'Linux amd64 Shared' + pool: + vmImage: 'ubuntu-16.04' + workspace: + clean: all + steps: +- - job: linux_amd64_static + displayName: 'Linux amd64 Static' + pool: + vmImage: 'ubuntu-16.04' + workspace: + clean: all + steps: +- - job: windows_386_msvc2015_shared + displayName: 'Windows 386 MSVC2015 Shared' + pool: + vmImage: 'vs2015-win2012r2' + workspace: + clean: all + steps: +- - job: windows_386_msvc2015_static + displayName: 'Windows 386 MSVC2015 Static' + pool: + vmImage: 'vs2015-win2012r2' + workspace: + clean: all + steps: +- - job: windows_amd64_msvc2015_shared + displayName: 'Windows amd64 MSVC2015 Shared' + pool: + vmImage: 'vs2015-win2012r2' + workspace: + clean: all + steps: +- - job: windows_amd64_msvc2015_static + displayName: 'Windows amd64 MSVC2015 Static' + pool: + vmImage: 'vs2015-win2012r2' + workspace: + clean: all + steps: +- - job: windows_386_msvc2017_shared + displayName: 'Windows 386 MSVC2017 Shared' + pool: + vmImage: 'vs2017-win2016' + workspace: + clean: all + steps: +- - job: windows_386_msvc2017_static + displayName: 'Windows 386 MSVC2017 Static' + pool: + vmImage: 'vs2017-win2016' + workspace: + clean: all + steps: +- - job: windows_amd64_msvc2017_shared + displayName: 'Windows amd64 MSVC2017 Shared' + pool: + vmImage: 'vs2017-win2016' + workspace: + clean: all + steps: +- - job: windows_amd64_msvc2017_static + displayName: 'Windows amd64 MSVC2017 Static' + pool: + vmImage: 'vs2017-win2016' + workspace: + clean: all + steps: +- - job: darwin_amd64_shared + displayName: 'Darwin amd64 Shared' + pool: + vmImage: 'macos-10.13' + workspace: + clean: all + steps: +- - job: darwin_amd64_static + displayName: 'Darwin amd64 Static' + pool: + vmImage: 'macos-10.13' + workspace: + clean: all + steps: +} +{ +- template: azure-pipelines/setup-python3.yml +- template: azure-pipelines/vs2015-install-python3.yml +} +- template: azure-pipelines/install-latest-meson-ninja.yml +{ +- template: azure-pipelines/linux-386-install-gtk-dev.yml +- template: azure-pipelines/linux-install-gtk-dev.yml +- template: azure-pipelines/windows-install-ninja.yml +- template: azure-pipelines/darwin-install-ninja.yml +} +{ +- template: azure-pipelines/configure.yml + parameters: + beforeConfigure: export CFLAGS=-m32 CXXFLAGS=-m32 PKG_CONFIG_PATH=/usr/lib/i386-linux-gnu/pkgconfig + defaultLibrary: shared +- template: azure-pipelines/configure.yml + parameters: + beforeConfigure: export CFLAGS=-m32 CXXFLAGS=-m32 PKG_CONFIG_PATH=/usr/lib/i386-linux-gnu/pkgconfig + defaultLibrary: static +- template: azure-pipelines/configure.yml + parameters: + defaultLibrary: shared +- template: azure-pipelines/configure.yml + parameters: + defaultLibrary: static +- template: azure-pipelines/configure.yml + parameters: + beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86 + defaultLibrary: shared +- template: azure-pipelines/configure.yml + parameters: + beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86 + defaultLibrary: static +- template: azure-pipelines/configure.yml + parameters: + beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" amd64 + defaultLibrary: shared +- template: azure-pipelines/configure.yml + parameters: + beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" amd64 + defaultLibrary: static +- template: azure-pipelines/configure.yml + parameters: + beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x86 + defaultLibrary: shared +- template: azure-pipelines/configure.yml + parameters: + beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x86 + defaultLibrary: static +- template: azure-pipelines/configure.yml + parameters: + beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" amd64 + defaultLibrary: shared +- template: azure-pipelines/configure.yml + parameters: + beforeConfigure: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" amd64 + defaultLibrary: static +} +{ +- template: azure-pipelines/build.yml +- template: azure-pipelines/build.yml + parameters: + beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86 +- template: azure-pipelines/build.yml + parameters: + beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86 + afterBuild: ren build\meson-out\libui.a libui.lib +- template: azure-pipelines/build.yml + parameters: + beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" amd64 +- template: azure-pipelines/build.yml + parameters: + beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" amd64 + afterBuild: ren build\meson-out\libui.a libui.lib +- template: azure-pipelines/build.yml + parameters: + beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x86 +- template: azure-pipelines/build.yml + parameters: + beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x86 + afterBuild: ren build\meson-out\libui.a libui.lib +- template: azure-pipelines/build.yml + parameters: + beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" amd64 +- template: azure-pipelines/build.yml + parameters: + beforeBuild: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" amd64 + afterBuild: ren build\meson-out\libui.a libui.lib +} +{ +- template: azure-pipelines/artifacts.yml + parameters: + os: linux + arch: 386 + libtype: shared + libfiles: libui.so.0 + osHeader: ui_unix.h +- template: azure-pipelines/artifacts.yml + parameters: + os: linux + arch: 386 + libtype: static + libfiles: libui.a + osHeader: ui_unix.h +- template: azure-pipelines/artifacts.yml + parameters: + os: linux + arch: amd64 + libtype: shared + libfiles: libui.so.0 + osHeader: ui_unix.h +- template: azure-pipelines/artifacts.yml + parameters: + os: linux + arch: amd64 + libtype: static + libfiles: libui.a + osHeader: ui_unix.h +- template: azure-pipelines/windows-artifacts.yml + parameters: + os: windows + arch: 386 + toolchain: msvc2015 + libtype: shared + libfiles: libui.dll libui.exp libui.lib + osHeader: ui_windows.h +- template: azure-pipelines/windows-artifacts.yml + parameters: + os: windows + arch: 386 + toolchain: msvc2015 + libtype: static + libfiles: libui.lib + osHeader: ui_windows.h +- template: azure-pipelines/windows-artifacts.yml + parameters: + os: windows + arch: amd64 + toolchain: msvc2015 + libtype: shared + libfiles: libui.dll libui.exp libui.lib + osHeader: ui_windows.h +- template: azure-pipelines/windows-artifacts.yml + parameters: + os: windows + arch: amd64 + toolchain: msvc2015 + libtype: static + libfiles: libui.lib + osHeader: ui_windows.h +- template: azure-pipelines/windows-artifacts.yml + parameters: + os: windows + arch: 386 + toolchain: msvc2017 + libtype: shared + libfiles: libui.dll libui.exp libui.lib + osHeader: ui_windows.h +- template: azure-pipelines/windows-artifacts.yml + parameters: + os: windows + arch: 386 + toolchain: msvc2017 + libtype: static + libfiles: libui.lib + osHeader: ui_windows.h +- template: azure-pipelines/windows-artifacts.yml + parameters: + os: windows + arch: amd64 + toolchain: msvc2017 + libtype: shared + libfiles: libui.dll libui.exp libui.lib + osHeader: ui_windows.h +- template: azure-pipelines/windows-artifacts.yml + parameters: + os: windows + arch: amd64 + toolchain: msvc2017 + libtype: static + libfiles: libui.lib + osHeader: ui_windows.h +- template: azure-pipelines/artifacts.yml + parameters: + os: darwin + arch: amd64 + libtype: shared + libfiles: libui.A.dylib + osHeader: ui_darwin.h +- template: azure-pipelines/artifacts.yml + parameters: + os: darwin + arch: amd64 + libtype: static + libfiles: libui.a + osHeader: ui_darwin.h +} diff --git a/dep/libui/azure-pipelines/configure.yml b/dep/libui/azure-pipelines/configure.yml new file mode 100644 index 0000000..aec307f --- /dev/null +++ b/dep/libui/azure-pipelines/configure.yml @@ -0,0 +1,11 @@ +# 5 april 2019 + +parameters: + beforeConfigure: '' + defaultLibrary: 'must-be-set' + +steps: +- script: | + ${{ parameters.beforeConfigure }} + meson setup build --buildtype=release --default-library=${{ parameters.defaultLibrary }} + displayName: 'Configure' diff --git a/dep/libui/azure-pipelines/darwin-install-ninja.yml b/dep/libui/azure-pipelines/darwin-install-ninja.yml new file mode 100644 index 0000000..4703017 --- /dev/null +++ b/dep/libui/azure-pipelines/darwin-install-ninja.yml @@ -0,0 +1,13 @@ +# 5 april 2019 +# because brew install is also slow (it runs an update task first) + +steps: +- script: | + sudo mkdir -p /opt/ninja + pushd /opt/ninja + sudo wget https://github.com/ninja-build/ninja/releases/download/v1.9.0/ninja-mac.zip + sudo unzip ninja-mac.zip + sudo chmod a+rx ninja + popd + echo '##vso[task.prependpath]/opt/ninja' + displayName: 'Install Ninja' diff --git a/dep/libui/azure-pipelines/install-latest-meson-ninja.yml b/dep/libui/azure-pipelines/install-latest-meson-ninja.yml new file mode 100644 index 0000000..d2934bc --- /dev/null +++ b/dep/libui/azure-pipelines/install-latest-meson-ninja.yml @@ -0,0 +1,9 @@ +# 4 april 2019 + +# TODO remove ninja installation from non-Linux OSs and make the same ninja via pip change in the AppVeyor script + +steps: +- script: | + python -m pip install --upgrade pip setuptools wheel + pip install meson ninja + displayName: 'Install Latest Meson and Ninja' diff --git a/dep/libui/azure-pipelines/linux-386-install-gtk-dev.yml b/dep/libui/azure-pipelines/linux-386-install-gtk-dev.yml new file mode 100644 index 0000000..42bf050 --- /dev/null +++ b/dep/libui/azure-pipelines/linux-386-install-gtk-dev.yml @@ -0,0 +1,17 @@ +# 7 april 2019 + +# TODO figure out how to get meson to recognize the compiler is producing 32-bit output + +steps: +- script: | + # Azure Pipelines ships with a patched version of this and that patch is only available on 64-bit systems, so trying to install the 32-bit versions will remove the 64-bit versions outright + # This is a dependency of Mesa, so we'll have to downgrade to the stock distro ones :/ + llvmPackages= + for i in libllvm6.0 clang-6.0 libclang-common-6.0-dev liblldb-6.0 liblldb-6.0-dev lld-6.0 lldb-6.0 llvm-6.0-dev python-lldb-6.0 libclang1-6.0 llvm-6.0 llvm-6.0-runtime; do llvmPackages="$llvmPackages $i=1:6.0-1ubuntu2~16.04.1"; done + sudo dpkg --add-architecture i386 + sudo apt-get update + sudo apt-get install --allow-downgrades \ + gcc-multilib g++-multilib \ + $llvmPackages \ + libgtk-3-dev:i386 + displayName: 'Install GTK+ Dev Files' diff --git a/dep/libui/azure-pipelines/linux-install-gtk-dev.yml b/dep/libui/azure-pipelines/linux-install-gtk-dev.yml new file mode 100644 index 0000000..b797fb7 --- /dev/null +++ b/dep/libui/azure-pipelines/linux-install-gtk-dev.yml @@ -0,0 +1,6 @@ +# 7 april 2019 + +steps: +- script: | + sudo apt-get install libgtk-3-dev + displayName: 'Install GTK+ Dev Files' diff --git a/dep/libui/azure-pipelines/setup-python3.yml b/dep/libui/azure-pipelines/setup-python3.yml new file mode 100644 index 0000000..7fe321e --- /dev/null +++ b/dep/libui/azure-pipelines/setup-python3.yml @@ -0,0 +1,7 @@ +# 4 april 2019 + +steps: +- task: UsePythonVersion@0 + inputs: + versionSpec: '3.6' + architecture: 'x64' diff --git a/dep/libui/azure-pipelines/vs2015-install-python3.yml b/dep/libui/azure-pipelines/vs2015-install-python3.yml new file mode 100644 index 0000000..93502fc --- /dev/null +++ b/dep/libui/azure-pipelines/vs2015-install-python3.yml @@ -0,0 +1,10 @@ +# 4 april 2019 +# see https://github.com/Microsoft/azure-pipelines-image-generation/issues/374 for context and source + +steps: +- script: | + powershell -Command "Invoke-WebRequest https://www.python.org/ftp/python/3.7.1/python-3.7.1-amd64-webinstall.exe -OutFile C:\py3-setup.exe" + C:\py3-setup.exe /quiet PrependPath=0 InstallAllUsers=0 Include_launcher=0 InstallLauncherAllUsers=0 Include_test=0 Include_doc=0 Include_dev=0 Include_debug=0 Include_tcltk=0 TargetDir=C:\Python37 + @echo ##vso[task.prependpath]C:\Python37 + @echo ##vso[task.prependpath]C:\Python37\Scripts + displayName: 'Install Python 3' diff --git a/dep/libui/azure-pipelines/windows-artifacts.yml b/dep/libui/azure-pipelines/windows-artifacts.yml new file mode 100644 index 0000000..172aac8 --- /dev/null +++ b/dep/libui/azure-pipelines/windows-artifacts.yml @@ -0,0 +1,28 @@ +# 6 april 2019 + +parameters: + os: '' + arch: '' + toolchain: '' + libtype: '' + libfiles: '' + osHeader: '' + +steps: +- powershell: | + pushd build\meson-out + Copy-Item @("..\..\ui.h","..\..\${{ parameters.osHeader }}") -Destination . + Compress-Archive -Destination $(Build.ArtifactStagingDirectory)\libui-$(Build.SourceBranchName)-${{ parameters.os }}-${{ parameters.arch }}-${{ parameters.toolchain }}-${{ parameters.libtype }}.zip -Path @("${{ parameters.libfiles }}".Split(" ") + @("ui.h","${{ parameters.osHeader}}")) + Compress-Archive -Destination $(Build.ArtifactStagingDirectory)\examples-$(Build.SourceBranchName)-${{ parameters.os }}-${{ parameters.arch }}-${{ parameters.libtype }}.zip -Path @("$(releaseExamples)".Split(" ") | % {$_ + ".exe"}) + Remove-Item @("ui.h","${{ parameters.osHeader }}") + popd + displayName: 'Create Artifacts' +- task: GitHubRelease@0 + condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/') + inputs: + gitHubConnection: andlabs + repositoryName: andlabs/libui + action: 'edit' + addChangelog: false + assets: '$(Build.ArtifactStagingDirectory)/*' + assetUploadMode: 'replace' diff --git a/dep/libui/azure-pipelines/windows-install-ninja.yml b/dep/libui/azure-pipelines/windows-install-ninja.yml new file mode 100644 index 0000000..d9fe366 --- /dev/null +++ b/dep/libui/azure-pipelines/windows-install-ninja.yml @@ -0,0 +1,10 @@ +# 4 april 2019 +# why this? because choco isn't available on the VS2015 image and is extremely slow on the VS2017 one (it should not take 2.5 minutes to install just ninja!) + +steps: +- script: | + powershell -Command "Invoke-WebRequest https://github.com/ninja-build/ninja/releases/download/v1.9.0/ninja-win.zip -OutFile C:\ninja-win.zip" + mkdir C:\ninja + powershell -Command "Expand-Archive -LiteralPath C:\ninja-win.zip -DestinationPath C:\ninja" + @echo ##vso[task.prependpath]C:\ninja + displayName: 'Install Ninja' diff --git a/dep/libui/common/OLD_table.c b/dep/libui/common/OLD_table.c new file mode 100644 index 0000000..3726883 --- /dev/null +++ b/dep/libui/common/OLD_table.c @@ -0,0 +1,22 @@ +// 21 june 2016 +#include "../ui.h" +#include "uipriv.h" + +void *uiTableModelGiveInt(int i) +{ + return (void *) ((intptr_t) i); +} + +int uiTableModelTakeInt(void *v) +{ + return (int) ((intptr_t) v); +} + +uiTableColumn *uiTableAppendTextColumn(uiTable *t, const char *name, int modelColumn) +{ + uiTableColumn *tc; + + tc = uiTableAppendColumn(t, name); + uiTableColumnAppendTextPart(tc, modelColumn, 1); + return tc; +} diff --git a/dep/libui/common/areaevents.c b/dep/libui/common/areaevents.c new file mode 100644 index 0000000..491a728 --- /dev/null +++ b/dep/libui/common/areaevents.c @@ -0,0 +1,169 @@ +// 29 march 2014 +#include "../ui.h" +#include "uipriv.h" + +/* +Windows and GTK+ have a limit of 2 and 3 clicks, respectively, natively supported. Fortunately, we can simulate the double/triple-click behavior to build higher-order clicks. We can use the same algorithm Windows uses on both: + http://blogs.msdn.com/b/oldnewthing/archive/2004/10/18/243925.aspx +For GTK+, we pull the double-click time and double-click distance, which work the same as the equivalents on Windows (so the distance is in all directions), from the GtkSettings system. + +On GTK+ this will also allow us to discard the GDK_BUTTON_2PRESS and GDK_BUTTON_3PRESS events, so the button press stream will be just like on other platforms. + +Thanks to mclasen, garnacho_, halfline, and tristan in irc.gimp.net/#gtk+. + +TODO note the bits about asymmetry and g_rcClick initial value not mattering in the oldnewthing article +*/ + +// x, y, xdist, ydist, and c.rect must have the same units +// so must time, maxTime, and c.prevTime +int uiprivClickCounterClick(uiprivClickCounter *c, int button, int x, int y, uintptr_t time, uintptr_t maxTime, int32_t xdist, int32_t ydist) +{ + // different button than before? if so, don't count + if (button != c->curButton) + c->count = 0; + + // (x, y) in the allowed region for a double-click? if not, don't count + if (x < c->rectX0) + c->count = 0; + if (y < c->rectY0) + c->count = 0; + if (x >= c->rectX1) + c->count = 0; + if (y >= c->rectY1) + c->count = 0; + + // too slow? if so, don't count + // note the below expression; time > (c.prevTime + maxTime) can overflow! + if ((time - c->prevTime) > maxTime) // too slow; don't count + c->count = 0; + + c->count++; // if either of the above ifs happened, this will make the click count 1; otherwise it will make the click count 2, 3, 4, 5, ... + + // now we need to update the internal structures for the next test + c->curButton = button; + c->prevTime = time; + c->rectX0 = x - xdist; + c->rectY0 = y - ydist; + c->rectX1 = x + xdist; + c->rectY1 = y + ydist; + + return c->count; +} + +void uiprivClickCounterReset(uiprivClickCounter *c) +{ + c->curButton = 0; + c->rectX0 = 0; + c->rectY0 = 0; + c->rectX1 = 0; + c->rectY1 = 0; + c->prevTime = 0; + c->count = 0; +} + +/* +For position independence across international keyboard layouts, typewriter keys are read using scancodes (which are always set 1). +Windows provides the scancodes directly in the LPARAM. +GTK+ provides the scancodes directly from the underlying window system via GdkEventKey.hardware_keycode. +On X11, this is scancode + 8 (because X11 keyboard codes have a range of [8,255]). +Wayland is guaranteed to give the same result (thanks ebassi in irc.gimp.net/#gtk+). +On Linux, where evdev is used instead of polling scancodes directly from the keyboard, evdev's typewriter section key code constants are the same as scancodes anyway, so the rules above apply. +Typewriter section scancodes are the same across international keyboards with some exceptions that have been accounted for (see KeyEvent's documentation); see http://www.quadibloc.com/comp/scan.htm for details. +Non-typewriter keys can be handled safely using constants provided by the respective backend API. + +Because GTK+ keysyms may or may not obey Num Lock, we also handle the 0-9 and . keys on the numeric keypad with scancodes (they match too). +*/ + +// use uintptr_t to be safe; the size of the scancode/hardware key code field on each platform is different +static const struct { + uintptr_t scancode; + char equiv; +} scancodeKeys[] = { + { 0x02, '1' }, + { 0x03, '2' }, + { 0x04, '3' }, + { 0x05, '4' }, + { 0x06, '5' }, + { 0x07, '6' }, + { 0x08, '7' }, + { 0x09, '8' }, + { 0x0A, '9' }, + { 0x0B, '0' }, + { 0x0C, '-' }, + { 0x0D, '=' }, + { 0x0E, '\b' }, + { 0x0F, '\t' }, + { 0x10, 'q' }, + { 0x11, 'w' }, + { 0x12, 'e' }, + { 0x13, 'r' }, + { 0x14, 't' }, + { 0x15, 'y' }, + { 0x16, 'u' }, + { 0x17, 'i' }, + { 0x18, 'o' }, + { 0x19, 'p' }, + { 0x1A, '[' }, + { 0x1B, ']' }, + { 0x1C, '\n' }, + { 0x1E, 'a' }, + { 0x1F, 's' }, + { 0x20, 'd' }, + { 0x21, 'f' }, + { 0x22, 'g' }, + { 0x23, 'h' }, + { 0x24, 'j' }, + { 0x25, 'k' }, + { 0x26, 'l' }, + { 0x27, ';' }, + { 0x28, '\'' }, + { 0x29, '`' }, + { 0x2B, '\\' }, + { 0x2C, 'z' }, + { 0x2D, 'x' }, + { 0x2E, 'c' }, + { 0x2F, 'v' }, + { 0x30, 'b' }, + { 0x31, 'n' }, + { 0x32, 'm' }, + { 0x33, ',' }, + { 0x34, '.' }, + { 0x35, '/' }, + { 0x39, ' ' }, + { 0xFFFF, 0 }, +}; + +static const struct { + uintptr_t scancode; + uiExtKey equiv; +} scancodeExtKeys[] = { + { 0x47, uiExtKeyN7 }, + { 0x48, uiExtKeyN8 }, + { 0x49, uiExtKeyN9 }, + { 0x4B, uiExtKeyN4 }, + { 0x4C, uiExtKeyN5 }, + { 0x4D, uiExtKeyN6 }, + { 0x4F, uiExtKeyN1 }, + { 0x50, uiExtKeyN2 }, + { 0x51, uiExtKeyN3 }, + { 0x52, uiExtKeyN0 }, + { 0x53, uiExtKeyNDot }, + { 0xFFFF, 0 }, +}; + +int uiprivFromScancode(uintptr_t scancode, uiAreaKeyEvent *ke) +{ + int i; + + for (i = 0; scancodeKeys[i].scancode != 0xFFFF; i++) + if (scancodeKeys[i].scancode == scancode) { + ke->Key = scancodeKeys[i].equiv; + return 1; + } + for (i = 0; scancodeExtKeys[i].scancode != 0xFFFF; i++) + if (scancodeExtKeys[i].scancode == scancode) { + ke->ExtKey = scancodeExtKeys[i].equiv; + return 1; + } + return 0; +} diff --git a/dep/libui/common/attribute.c b/dep/libui/common/attribute.c new file mode 100644 index 0000000..4a8f016 --- /dev/null +++ b/dep/libui/common/attribute.c @@ -0,0 +1,266 @@ +// 19 february 2018 +#include "../ui.h" +#include "uipriv.h" +#include "attrstr.h" + +struct uiAttribute { + int ownedByUser; + size_t refcount; + uiAttributeType type; + union { + char *family; + double size; + uiTextWeight weight; + uiTextItalic italic; + uiTextStretch stretch; + struct { + double r; + double g; + double b; + double a; + // put this here so we can reuse this structure + uiUnderlineColor underlineColor; + } color; + uiUnderline underline; + uiOpenTypeFeatures *features; + } u; +}; + +static uiAttribute *newAttribute(uiAttributeType type) +{ + uiAttribute *a; + + a = uiprivNew(uiAttribute); + a->ownedByUser = 1; + a->refcount = 0; + a->type = type; + return a; +} + +// returns a to allow expressions like b = uiprivAttributeRetain(a) +// TODO would this allow us to copy attributes between strings in a foreach func, and if so, should that be allowed? +uiAttribute *uiprivAttributeRetain(uiAttribute *a) +{ + a->ownedByUser = 0; + a->refcount++; + return a; +} + +static void destroy(uiAttribute *a) +{ + switch (a->type) { + case uiAttributeTypeFamily: + uiprivFree(a->u.family); + break; + case uiAttributeTypeFeatures: + uiFreeOpenTypeFeatures(a->u.features); + break; + } + uiprivFree(a); +} + +void uiprivAttributeRelease(uiAttribute *a) +{ + if (a->ownedByUser) + /* TODO implementation bug: we can't release an attribute we don't own */; + a->refcount--; + if (a->refcount == 0) + destroy(a); +} + +void uiFreeAttribute(uiAttribute *a) +{ + if (!a->ownedByUser) + /* TODO user bug: you can't free an attribute you don't own */; + destroy(a); +} + +uiAttributeType uiAttributeGetType(const uiAttribute *a) +{ + return a->type; +} + +uiAttribute *uiNewFamilyAttribute(const char *family) +{ + uiAttribute *a; + + a = newAttribute(uiAttributeTypeFamily); + a->u.family = (char *) uiprivAlloc((strlen(family) + 1) * sizeof (char), "char[] (uiAttribute)"); + strcpy(a->u.family, family); + return a; +} + +const char *uiAttributeFamily(const uiAttribute *a) +{ + return a->u.family; +} + +uiAttribute *uiNewSizeAttribute(double size) +{ + uiAttribute *a; + + a = newAttribute(uiAttributeTypeSize); + a->u.size = size; + return a; +} + +double uiAttributeSize(const uiAttribute *a) +{ + return a->u.size; +} + +uiAttribute *uiNewWeightAttribute(uiTextWeight weight) +{ + uiAttribute *a; + + a = newAttribute(uiAttributeTypeWeight); + a->u.weight = weight; + return a; +} + +uiTextWeight uiAttributeWeight(const uiAttribute *a) +{ + return a->u.weight; +} + +uiAttribute *uiNewItalicAttribute(uiTextItalic italic) +{ + uiAttribute *a; + + a = newAttribute(uiAttributeTypeItalic); + a->u.italic = italic; + return a; +} + +uiTextItalic uiAttributeItalic(const uiAttribute *a) +{ + return a->u.italic; +} + +uiAttribute *uiNewStretchAttribute(uiTextStretch stretch) +{ + uiAttribute *a; + + a = newAttribute(uiAttributeTypeStretch); + a->u.stretch = stretch; + return a; +} + +uiTextStretch uiAttributeStretch(const uiAttribute *a) +{ + return a->u.stretch; +} + +uiAttribute *uiNewColorAttribute(double r, double g, double b, double a) +{ + uiAttribute *at; + + at = newAttribute(uiAttributeTypeColor); + at->u.color.r = r; + at->u.color.g = g; + at->u.color.b = b; + at->u.color.a = a; + return at; +} + +void uiAttributeColor(const uiAttribute *a, double *r, double *g, double *b, double *alpha) +{ + *r = a->u.color.r; + *g = a->u.color.g; + *b = a->u.color.b; + *alpha = a->u.color.a; +} + +uiAttribute *uiNewBackgroundAttribute(double r, double g, double b, double a) +{ + uiAttribute *at; + + at = newAttribute(uiAttributeTypeBackground); + at->u.color.r = r; + at->u.color.g = g; + at->u.color.b = b; + at->u.color.a = a; + return at; +} + +uiAttribute *uiNewUnderlineAttribute(uiUnderline u) +{ + uiAttribute *a; + + a = newAttribute(uiAttributeTypeUnderline); + a->u.underline = u; + return a; +} + +uiUnderline uiAttributeUnderline(const uiAttribute *a) +{ + return a->u.underline; +} + +uiAttribute *uiNewUnderlineColorAttribute(uiUnderlineColor u, double r, double g, double b, double a) +{ + uiAttribute *at; + + at = uiNewColorAttribute(r, g, b, a); + at->type = uiAttributeTypeUnderlineColor; + at->u.color.underlineColor = u; + return at; +} + +void uiAttributeUnderlineColor(const uiAttribute *a, uiUnderlineColor *u, double *r, double *g, double *b, double *alpha) +{ + *u = a->u.color.underlineColor; + uiAttributeColor(a, r, g, b, alpha); +} + +uiAttribute *uiNewFeaturesAttribute(const uiOpenTypeFeatures *otf) +{ + uiAttribute *a; + + a = newAttribute(uiAttributeTypeFeatures); + a->u.features = uiOpenTypeFeaturesClone(otf); + return a; +} + +const uiOpenTypeFeatures *uiAttributeFeatures(const uiAttribute *a) +{ + return a->u.features; +} + +int uiprivAttributeEqual(const uiAttribute *a, const uiAttribute *b) +{ + if (a == b) + return 1; + if (a->type != b->type) + return 0; + switch (a->type) { + case uiAttributeTypeFamily: + return uiprivStricmp(a->u.family, b->u.family); + case uiAttributeTypeSize: + // TODO is the use of == correct? + return a->u.size == b->u.size; + case uiAttributeTypeWeight: + return a->u.weight == b->u.weight; + case uiAttributeTypeItalic: + return a->u.italic == b->u.italic; + case uiAttributeTypeStretch: + return a->u.stretch == b->u.stretch; + case uiAttributeTypeUnderline: + return a->u.underline == b->u.underline; + case uiAttributeTypeUnderlineColor: + if (a->u.color.underlineColor != b->u.color.underlineColor) + return 0; + // fall through + case uiAttributeTypeColor: + case uiAttributeTypeBackground: + // TODO is the use of == correct? + return (a->u.color.r == b->u.color.r) && + (a->u.color.g == b->u.color.g) && + (a->u.color.b == b->u.color.b) && + (a->u.color.a == b->u.color.a); + case uiAttributeTypeFeatures: + return uiprivOpenTypeFeaturesEqual(a->u.features, b->u.features); + } + // TODO should not be reached + return 0; +} diff --git a/dep/libui/common/attrlist.c b/dep/libui/common/attrlist.c new file mode 100644 index 0000000..377778e --- /dev/null +++ b/dep/libui/common/attrlist.c @@ -0,0 +1,612 @@ +// 16 december 2016 +#include "../ui.h" +#include "uipriv.h" +#include "attrstr.h" + +/* +An attribute list is a doubly linked list of attributes. +Attribute start positions are inclusive and attribute end positions are exclusive (or in other words, [start, end)). +The list is kept sorted in increasing order by start position. Whether or not the sort is stable is undefined, so no temporal information should be expected to stay. +Overlapping attributes are not allowed; if an attribute is added that conflicts with an existing one, the existing one is removed. +In addition, the linked list tries to reduce fragmentation: if an attribute is added that just expands another, then there will only be one entry in alist, not two. (TODO does it really?) +The linked list is not a ring; alist->fist->prev == NULL and alist->last->next == NULL. +TODO verify that this disallows attributes of length zero +*/ + +struct attr { + uiAttribute *val; + size_t start; + size_t end; + struct attr *prev; + struct attr *next; +}; + +struct uiprivAttrList { + struct attr *first; + struct attr *last; +}; + +// if before is NULL, add to the end of the list +static void attrInsertBefore(uiprivAttrList *alist, struct attr *a, struct attr *before) +{ + // if the list is empty, this is the first item + if (alist->first == NULL) { + alist->first = a; + alist->last = a; + return; + } + + // add to the end + if (before == NULL) { + struct attr *oldlast; + + oldlast = alist->last; + alist->last = a; + a->prev = oldlast; + oldlast->next = a; + return; + } + + // add to the beginning + if (before == alist->first) { + struct attr *oldfirst; + + oldfirst = alist->first; + alist->first = a; + oldfirst->prev = a; + a->next = oldfirst; + return; + } + + // add to the middle + a->prev = before->prev; + a->next = before; + before->prev = a; + a->prev->next = a; +} + +static int attrHasPos(struct attr *a, size_t pos) +{ + if (pos < a->start) + return 0; + return pos < a->end; +} + +// returns 1 if there was an intersection and 0 otherwise +static int attrRangeIntersect(struct attr *a, size_t *start, size_t *end) +{ + // is the range outside a entirely? + if (*start >= a->end) + return 0; + if (*end < a->start) + return 0; + + // okay, so there is an overlap + // compute the intersection + if (*start < a->start) + *start = a->start; + if (*end > a->end) + *end = a->end; + return 1; +} + +// returns the old a->next, for forward iteration +static struct attr *attrUnlink(uiprivAttrList *alist, struct attr *a) +{ + struct attr *p, *n; + + p = a->prev; + n = a->next; + a->prev = NULL; + a->next = NULL; + + // only item in list? + if (p == NULL && n == NULL) { + alist->first = NULL; + alist->last = NULL; + return NULL; + } + // start of list? + if (p == NULL) { + n->prev = NULL; + alist->first = n; + return n; + } + // end of list? + if (n == NULL) { + p->next = NULL; + alist->last = p; + return NULL; + } + // middle of list + p->next = n; + n->prev = p; + return n; +} + +// returns the old a->next, for forward iteration +static struct attr *attrDelete(uiprivAttrList *alist, struct attr *a) +{ + struct attr *next; + + next = attrUnlink(alist, a); + uiprivAttributeRelease(a->val); + uiprivFree(a); + return next; +} + +// attrDropRange() removes attributes without deleting characters. +// +// If the attribute needs no change, then nothing is done. +// +// If the attribute needs to be deleted, it is deleted. +// +// If the attribute only needs to be resized at the end, it is adjusted. +// +// If the attribute only needs to be resized at the start, it is adjusted, unlinked, and returned in tail. +// +// Otherwise, the attribute needs to be split. The existing attribute is adjusted to make the left half and a new attribute with the right half. This attribute is kept unlinked and returned in tail. +// +// In all cases, the return value is the next attribute to look at in a forward sequential loop. +static struct attr *attrDropRange(uiprivAttrList *alist, struct attr *a, size_t start, size_t end, struct attr **tail) +{ + struct attr *b; + + // always pre-initialize tail to NULL + *tail = NULL; + + if (!attrRangeIntersect(a, &start, &end)) + // out of range; nothing to do + return a->next; + + // just outright delete the attribute? + // the inequalities handle attributes entirely inside the range + // if both are equal, the attribute's range is equal to the range + if (a->start >= start && a->end <= end) + return attrDelete(alist, a); + + // only chop off the start or end? + if (a->start == start) { // chop off the start + // we are dropping the left half, so set a->start and unlink + a->start = end; + *tail = a; + return attrUnlink(alist, a); + } + if (a->end == end) { // chop off the end + // we are dropping the right half, so just set a->end + a->end = start; + return a->next; + } + + // we'll need to split the attribute into two + b = uiprivNew(struct attr); + b->val = uiprivAttributeRetain(a->val); + b->start = end; + b->end = a->end; + *tail = b; + + a->end = start; + return a->next; +} + +static void attrGrow(uiprivAttrList *alist, struct attr *a, size_t start, size_t end) +{ + struct attr *before; + + // adjusting the end is simple: if it ends before our new end, just set the new end + if (a->end < end) + a->end = end; + + // adjusting the start is harder + // if the start is before our new start, we are done + // otherwise, we have to move the start back AND reposition the attribute to keep the sorted order + if (a->start <= start) + return; + a->start = start; + attrUnlink(alist, a); + for (before = alist->first; before != NULL; before = before->next) + if (before->start > a->start) + break; + attrInsertBefore(alist, a, before); +} + +// returns the right side of the split, which is unlinked, or NULL if no split was done +static struct attr *attrSplitAt(uiprivAttrList *alist, struct attr *a, size_t at) +{ + struct attr *b; + + // no splittng needed? + // note the equality: we don't need to split at start or end + // in the end case, the last split point is at - 1; at itself is outside the range, and at - 1 results in the right hand side having length 1 + if (at <= a->start) + return NULL; + if (at >= a->end) + return NULL; + + b = uiprivNew(struct attr); + b->val = uiprivAttributeRetain(a->val); + b->start = at; + b->end = a->end; + + a->end = at; + return b; +} + +// attrDeleteRange() removes attributes while deleting characters. +// +// If the attribute does not include the deleted range, then nothing is done (though the start and end are adjusted as necessary). +// +// If the attribute needs to be deleted, it is deleted. +// +// Otherwise, the attribute only needs the start or end deleted, and it is adjusted. +// +// In all cases, the return value is the next attribute to look at in a forward sequential loop. +// TODO rewrite this comment +static struct attr *attrDeleteRange(uiprivAttrList *alist, struct attr *a, size_t start, size_t end) +{ + size_t ostart, oend; + size_t count; + + ostart = start; + oend = end; + count = oend - ostart; + + if (!attrRangeIntersect(a, &start, &end)) { + // out of range + // adjust if necessary + if (a->start >= ostart) + a->start -= count; + if (a->end >= oend) + a->end -= count; + return a->next; + } + + // just outright delete the attribute? + // the inequalities handle attributes entirely inside the range + // if both are equal, the attribute's range is equal to the range + if (a->start >= start && a->end <= end) + return attrDelete(alist, a); + + // only chop off the start or end? + if (a->start == start) { // chop off the start + // if we weren't adjusting positions this would just be setting a->start to end + // but since this is deleting from the start, we need to adjust both by count + a->start = end - count; + a->end -= count; + return a->next; + } + if (a->end == end) { // chop off the end + // a->start is already good + a->end = start; + return a->next; + } + + // in this case, the deleted range is inside the attribute + // we can clear it by just removing count from a->end + a->end -= count; + return a->next; +} + +uiprivAttrList *uiprivNewAttrList(void) +{ + return uiprivNew(uiprivAttrList); +} + +void uiprivFreeAttrList(uiprivAttrList *alist) +{ + struct attr *a, *next; + + a = alist->first; + while (a != NULL) { + next = a->next; + uiprivAttributeRelease(a->val); + uiprivFree(a); + a = next; + } + uiprivFree(alist); +} + +void uiprivAttrListInsertAttribute(uiprivAttrList *alist, uiAttribute *val, size_t start, size_t end) +{ + struct attr *a; + struct attr *before; + struct attr *tail = NULL; + int split = 0; + uiAttributeType valtype; + + // first, figure out where in the list this should go + // in addition, if this attribute overrides one that already exists, split that one apart so this one can take over + before = alist->first; + valtype = uiAttributeGetType(val); + while (before != NULL) { + size_t lstart, lend; + + // once we get to the first point after start, we know where to insert + if (before->start > start) + break; + + // if we have already split a prior instance of this attribute, don't bother doing it again + if (split) + goto next; + + // should we split this attribute? + if (uiAttributeGetType(before->val) != valtype) + goto next; + lstart = start; + lend = end; + if (!attrRangeIntersect(before, &lstart, &lend)) + goto next; + + // okay so this might conflict; if the val is the same as the one we want, we need to expand the existing attribute, not fragment anything + // TODO will this reduce fragmentation if we first add from 0 to 2 and then from 2 to 4? or do we have to do that separately? + if (uiprivAttributeEqual(before->val, val)) { + attrGrow(alist, before, start, end); + return; + } + // okay the values are different; we need to split apart + before = attrDropRange(alist, before, start, end, &tail); + split = 1; + continue; + + next: + before = before->next; + } + + // if we got here, we know we have to add the attribute before before + a = uiprivNew(struct attr); + a->val = uiprivAttributeRetain(val); + a->start = start; + a->end = end; + attrInsertBefore(alist, a, before); + + // and finally, if we split, insert the remainder + if (tail == NULL) + return; + // note we start at before; it won't be inserted before that by the sheer nature of how the code above works + for (; before != NULL; before = before->next) + if (before->start > tail->start) + break; + attrInsertBefore(alist, tail, before); +} + +void uiprivAttrListInsertCharactersUnattributed(uiprivAttrList *alist, size_t start, size_t count) +{ + struct attr *a; + struct attr *tails = NULL; + + // every attribute before the insertion point can either cross into the insertion point or not + // if it does, we need to split that attribute apart at the insertion point, keeping only the old attribute in place, adjusting the new tail, and preparing it for being re-added later + for (a = alist->first; a != NULL; a = a->next) { + struct attr *tail; + + // stop once we get to the insertion point + if (a->start >= start) + break; + // only do something if overlapping + if (!attrHasPos(a, start)) + continue; + + tail = attrSplitAt(alist, a, start); + // adjust the new tail for the insertion + tail->start += count; + tail->end += count; + // and queue it for re-adding later + // we can safely use tails as if it was singly-linked since it's just a temporary list; we properly merge them back in below and they'll be doubly-linked again then + // TODO actually we could probably save some time by making then doubly-linked now and adding them in one fell swoop, but that would make things a bit more complicated... + tail->next = tails; + tails = tail; + } + + // at this point in the attribute list, we are at or after the insertion point + // all the split-apart attributes will be at the insertion point + // therefore, we can just add them all back now, and the list will still be sorted correctly + while (tails != NULL) { + struct attr *next; + + // make all the links NULL before insertion, just to be safe + next = tails->next; + tails->next = NULL; + attrInsertBefore(alist, tails, a); + tails = next; + } + + // every remaining attribute will be either at or after the insertion point + // we just need to move them ahead + for (; a != NULL; a = a->next) { + a->start += count; + a->end += count; + } +} + +// The attributes are those of character start - 1. +// If start == 0, the attributes are those of character 0. +/* +This is an obtuse function. Here's some diagrams to help. + +Given the input string + abcdefghi (positions: 012345678 9) +and attribute set + red start 0 end 3 + bold start 2 end 6 + underline start 5 end 8 +or visually: + 012345678 9 + rrr------ + --bbbb--- + -----uuu- +If we insert qwe to result in positions 0123456789AB C: + +before 0, 1, 2 (grow the red part, move everything else down) + red -> start 0 (no change) end 3+3=6 + bold -> start 2+3=5 end 6+3=9 + underline -> start 5+3=8 end 8+3=B +before 3 (grow red and bold, move underline down) + red -> start 0 (no change) end 3+3=6 + bold -> start 2 (no change) end 6+3=9 + underline -> start 5+3=8 end 8+3=B +before 4, 5 (keep red, grow bold, move underline down) + red -> start 0 (no change) end 3 (no change) + bold -> start 2 (no change) end 6+3=9 + underline -> start 5+3=8 end 8+3=B +before 6 (keep red, grow bold and underline) + red -> start 0 (no change) end 3 (no change) + bold -> start 2 (no change) end 6+3=9 + underline -> start 5 (no change) end 8+3=B +before 7, 8 (keep red and bold, grow underline) + red -> start 0 (no change) end 3 (no change) + bold -> start 2 (no change) end 6 (no change) + underline -> start 5 (no change) end 8+3=B +before 9 (keep all three) + red -> start 0 (no change) end 3 (no change) + bold -> start 2 (no change) end 6 (no change) + underline -> start 5 (no change) end 8 (no change) + +result: + 0 1 2 3 4 5 6 7 8 9 + red E E E e n n n n n n + bold s s S E E E e n n n +underline s s s s s S E E e n +N = none +E = end only +S = start and end +uppercase = in original range, lowercase = not + +which results in our algorithm: + for each attribute + if start < insertion point + move start up + else if start == insertion point + if start != 0 + move start up + if end <= insertion point + move end up +*/ +// TODO does this ensure the list remains sorted? +void uiprivAttrListInsertCharactersExtendingAttributes(uiprivAttrList *alist, size_t start, size_t count) +{ + struct attr *a; + + for (a = alist->first; a != NULL; a = a->next) { + if (a->start < start) + a->start += count; + else if (a->start == start && start != 0) + a->start += count; + if (a->end <= start) + a->end += count; + } +} + +// TODO replace at point with — replaces with first character's attributes + +void uiprivAttrListRemoveAttribute(uiprivAttrList *alist, uiAttributeType type, size_t start, size_t end) +{ + struct attr *a; + struct attr *tails = NULL; // see uiprivAttrListInsertCharactersUnattributed() above + struct attr *tailsAt = NULL; + + a = alist->first; + while (a != NULL) { + size_t lstart, lend; + struct attr *tail; + + // this defines where to re-attach the tails + // (all the tails will have their start at end, so we can just insert them all before tailsAt) + if (a->start >= end) { + tailsAt = a; + // and at this point we're done, so + break; + } + if (uiAttributeGetType(a->val) != type) + goto next; + lstart = start; + lend = end; + if (!attrRangeIntersect(a, &lstart, &lend)) + goto next; + a = attrDropRange(alist, a, start, end, &tail); + if (tail != NULL) { + tail->next = tails; + tails = tail; + } + continue; + + next: + a = a->next; + } + + while (tails != NULL) { + struct attr *next; + + // make all the links NULL before insertion, just to be safe + next = tails->next; + tails->next = NULL; + attrInsertBefore(alist, tails, a); + tails = next; + } +} + +// TODO merge this with the above +void uiprivAttrListRemoveAttributes(uiprivAttrList *alist, size_t start, size_t end) +{ + struct attr *a; + struct attr *tails = NULL; // see uiprivAttrListInsertCharactersUnattributed() above + struct attr *tailsAt = NULL; + + a = alist->first; + while (a != NULL) { + size_t lstart, lend; + struct attr *tail; + + // this defines where to re-attach the tails + // (all the tails will have their start at end, so we can just insert them all before tailsAt) + if (a->start >= end) { + tailsAt = a; + // and at this point we're done, so + break; + } + lstart = start; + lend = end; + if (!attrRangeIntersect(a, &lstart, &lend)) + goto next; + a = attrDropRange(alist, a, start, end, &tail); + if (tail != NULL) { + tail->next = tails; + tails = tail; + } + continue; + + next: + a = a->next; + } + + while (tails != NULL) { + struct attr *next; + + // make all the links NULL before insertion, just to be safe + next = tails->next; + tails->next = NULL; + attrInsertBefore(alist, tails, a); + tails = next; + } +} + +void uiprivAttrListRemoveCharacters(uiprivAttrList *alist, size_t start, size_t end) +{ + struct attr *a; + + a = alist->first; + while (a != NULL) + a = attrDeleteRange(alist, a, start, end); +} + +void uiprivAttrListForEach(const uiprivAttrList *alist, const uiAttributedString *s, uiAttributedStringForEachAttributeFunc f, void *data) +{ + struct attr *a; + uiForEach ret; + + for (a = alist->first; a != NULL; a = a->next) { + ret = (*f)(s, a->val, a->start, a->end, data); + if (ret == uiForEachStop) + // TODO for all: break or return? + break; + } +} diff --git a/dep/libui/common/attrstr.c b/dep/libui/common/attrstr.c new file mode 100644 index 0000000..ca00c19 --- /dev/null +++ b/dep/libui/common/attrstr.c @@ -0,0 +1,357 @@ +// 3 december 2016 +#include "../ui.h" +#include "uipriv.h" +#include "attrstr.h" + +struct uiAttributedString { + char *s; + size_t len; + + uiprivAttrList *attrs; + + // indiscriminately keep a UTF-16 copy of the string on all platforms so we can hand this off to the grapheme calculator + // this ensures no one platform has a speed advantage (sorry GTK+) + uint16_t *u16; + size_t u16len; + + size_t *u8tou16; + size_t *u16tou8; + + // this is lazily created to keep things from getting *too* slow + uiprivGraphemes *graphemes; +}; + +static void resize(uiAttributedString *s, size_t u8, size_t u16) +{ + s->len = u8; + s->s = (char *) uiprivRealloc(s->s, (s->len + 1) * sizeof (char), "char[] (uiAttributedString)"); + s->u8tou16 = (size_t *) uiprivRealloc(s->u8tou16, (s->len + 1) * sizeof (size_t), "size_t[] (uiAttributedString)"); + s->u16len = u16; + s->u16 = (uint16_t *) uiprivRealloc(s->u16, (s->u16len + 1) * sizeof (uint16_t), "uint16_t[] (uiAttributedString)"); + s->u16tou8 = (size_t *) uiprivRealloc(s->u16tou8, (s->u16len + 1) * sizeof (size_t), "size_t[] (uiAttributedString)"); +} + +uiAttributedString *uiNewAttributedString(const char *initialString) +{ + uiAttributedString *s; + + s = uiprivNew(uiAttributedString); + s->attrs = uiprivNewAttrList(); + uiAttributedStringAppendUnattributed(s, initialString); + return s; +} + +// TODO make sure that all implementations of uiprivNewGraphemes() work fine with empty strings; in particular, the Windows one might not +static void recomputeGraphemes(uiAttributedString *s) +{ + if (s->graphemes != NULL) + return; + if (uiprivGraphemesTakesUTF16()) { + s->graphemes = uiprivNewGraphemes(s->u16, s->u16len); + return; + } + s->graphemes = uiprivNewGraphemes(s->s, s->len); +} + +static void invalidateGraphemes(uiAttributedString *s) +{ + if (s->graphemes == NULL) + return; + uiprivFree(s->graphemes->pointsToGraphemes); + uiprivFree(s->graphemes->graphemesToPoints); + uiprivFree(s->graphemes); + s->graphemes = NULL; +} + +void uiFreeAttributedString(uiAttributedString *s) +{ + uiprivFreeAttrList(s->attrs); + invalidateGraphemes(s); + uiprivFree(s->u16tou8); + uiprivFree(s->u8tou16); + uiprivFree(s->u16); + uiprivFree(s->s); + uiprivFree(s); +} + +const char *uiAttributedStringString(const uiAttributedString *s) +{ + return s->s; +} + +size_t uiAttributedStringLen(const uiAttributedString *s) +{ + return s->len; +} + +static void u8u16len(const char *str, size_t *n8, size_t *n16) +{ + uint32_t rune; + char buf[4]; + uint16_t buf16[2]; + + *n8 = 0; + *n16 = 0; + while (*str) { + str = uiprivUTF8DecodeRune(str, 0, &rune); + // TODO document the use of the function vs a pointer subtract here + // TODO also we need to consider namespace collision with utf.h... + *n8 += uiprivUTF8EncodeRune(rune, buf); + *n16 += uiprivUTF16EncodeRune(rune, buf16); + } +} + +void uiAttributedStringAppendUnattributed(uiAttributedString *s, const char *str) +{ + uiAttributedStringInsertAtUnattributed(s, str, s->len); +} + +// this works (and returns true, which is what we want) at s->len too because s->s[s->len] is always going to be 0 due to us allocating s->len + 1 bytes and because uiprivRealloc() always zero-fills allocated memory +static int onCodepointBoundary(uiAttributedString *s, size_t at) +{ + uint8_t c; + + // for uiNewAttributedString() + if (s->s == NULL && at == 0) + return 1; + c = (uint8_t) (s->s[at]); + return c < 0x80 || c >= 0xC0; +} + +// TODO note that at must be on a codeoint boundary +void uiAttributedStringInsertAtUnattributed(uiAttributedString *s, const char *str, size_t at) +{ + uint32_t rune; + char buf[4]; + uint16_t buf16[2]; + size_t n8, n16; // TODO make loop-local? to avoid using them in the wrong place again + size_t old, old16; + size_t oldn8, oldn16; + size_t oldlen, old16len; + size_t at16; + size_t i; + + if (!onCodepointBoundary(s, at)) { + // TODO + } + + at16 = 0; + if (s->u8tou16 != NULL) + at16 = s->u8tou16[at]; + + // do this first to reclaim memory + invalidateGraphemes(s); + + // first figure out how much we need to grow by + // this includes post-validated UTF-8 + u8u16len(str, &n8, &n16); + + // and resize + old = at; + old16 = at16; + oldlen = s->len; + old16len = s->u16len; + resize(s, s->len + n8, s->u16len + n16); + + // move existing characters out of the way + // note the use of memmove(): https://twitter.com/rob_pike/status/737797688217894912 + memmove( + s->s + at + n8, + s->s + at, + (oldlen - at) * sizeof (char)); + memmove( + s->u16 + at16 + n16, + s->u16 + at16, + (old16len - at16) * sizeof (uint16_t)); + // note the + 1 for these; we want to copy the terminating null too + memmove( + s->u8tou16 + at + n8, + s->u8tou16 + at, + (oldlen - at + 1) * sizeof (size_t)); + memmove( + s->u16tou8 + at16 + n16, + s->u16tou8 + at16, + (old16len - at16 + 1) * sizeof (size_t)); + oldn8 = n8; + oldn16 = n16; + + // and copy + while (*str) { + size_t n; + + str = uiprivUTF8DecodeRune(str, 0, &rune); + n = uiprivUTF8EncodeRune(rune, buf); + n16 = uiprivUTF16EncodeRune(rune, buf16); + s->s[old] = buf[0]; + s->u8tou16[old] = old16; + if (n > 1) { + s->s[old + 1] = buf[1]; + s->u8tou16[old + 1] = old16; + } + if (n > 2) { + s->s[old + 2] = buf[2]; + s->u8tou16[old + 2] = old16; + } + if (n > 3) { + s->s[old + 3] = buf[3]; + s->u8tou16[old + 3] = old16; + } + s->u16[old16] = buf16[0]; + s->u16tou8[old16] = old; + if (n16 > 1) { + s->u16[old16 + 1] = buf16[1]; + s->u16tou8[old16 + 1] = old; + } + old += n; + old16 += n16; + } + // and have an index for the end of the string + // TODO is this done by the below? +//TODO s->u8tou16[old] = old16; +//TODO s->u16tou8[old16] = old; + + // and adjust the prior values in the conversion tables + // use <= so the terminating 0 gets updated too + for (i = 0; i <= oldlen - at; i++) + s->u8tou16[at + oldn8 + i] += s->u16len - old16len; + for (i = 0; i <= old16len - at16; i++) + s->u16tou8[at16 + oldn16 + i] += s->len - oldlen; + + // and finally do the attributes + uiprivAttrListInsertCharactersUnattributed(s->attrs, at, n8); +} + +// TODO document that end is the first index that will be maintained +void uiAttributedStringDelete(uiAttributedString *s, size_t start, size_t end) +{ + size_t start16, end16; + size_t count, count16; + size_t i; + + if (!onCodepointBoundary(s, start)) { + // TODO + } + if (!onCodepointBoundary(s, end)) { + // TODO + } + + count = end - start; + start16 = s->u8tou16[start]; + end16 = s->u8tou16[end]; + count16 = end16 - start16; + + invalidateGraphemes(s); + + // overwrite old characters + memmove( + s->s + start, + s->s + end, + (s->len - end) * sizeof (char)); + memmove( + s->u16 + start16, + s->u16 + end16, + (s->u16len - end16) * sizeof (uint16_t)); + // note the + 1 for these; we want to copy the terminating null too + memmove( + s->u8tou16 + start, + s->u8tou16 + end, + (s->len - end + 1) * sizeof (size_t)); + memmove( + s->u16tou8 + start16, + s->u16tou8 + end16, + (s->u16len - end16 + 1) * sizeof (size_t)); + + // update the conversion tables + // note the use of <= to include the null terminator + for (i = 0; i <= (s->len - end); i++) + s->u8tou16[start + i] -= count16; + for (i = 0; i <= (s->u16len - end16); i++) + s->u16tou8[start16 + i] -= count; + + // null-terminate the string + s->s[start + (s->len - end)] = 0; + s->u16[start16 + (s->u16len - end16)] = 0; + + // fix up attributes + uiprivAttrListRemoveCharacters(s->attrs, start, end); + + // and finally resize + resize(s, s->len - count, s->u16len - count16); +} + +void uiAttributedStringSetAttribute(uiAttributedString *s, uiAttribute *a, size_t start, size_t end) +{ + uiprivAttrListInsertAttribute(s->attrs, a, start, end); +} + +// LONGTERM introduce an iterator object instead? +void uiAttributedStringForEachAttribute(const uiAttributedString *s, uiAttributedStringForEachAttributeFunc f, void *data) +{ + uiprivAttrListForEach(s->attrs, s, f, data); +} + +// TODO figure out if we should count the grapheme past the end +size_t uiAttributedStringNumGraphemes(uiAttributedString *s) +{ + recomputeGraphemes(s); + return s->graphemes->len; +} + +size_t uiAttributedStringByteIndexToGrapheme(uiAttributedString *s, size_t pos) +{ + recomputeGraphemes(s); + if (uiprivGraphemesTakesUTF16()) + pos = s->u8tou16[pos]; + return s->graphemes->pointsToGraphemes[pos]; +} + +size_t uiAttributedStringGraphemeToByteIndex(uiAttributedString *s, size_t pos) +{ + recomputeGraphemes(s); + pos = s->graphemes->graphemesToPoints[pos]; + if (uiprivGraphemesTakesUTF16()) + pos = s->u16tou8[pos]; + return pos; +} + +// helpers for platform-specific code + +const uint16_t *uiprivAttributedStringUTF16String(const uiAttributedString *s) +{ + return s->u16; +} + +size_t uiprivAttributedStringUTF16Len(const uiAttributedString *s) +{ + return s->u16len; +} + +// TODO is this still needed given the below? +size_t uiprivAttributedStringUTF8ToUTF16(const uiAttributedString *s, size_t n) +{ + return s->u8tou16[n]; +} + +size_t *uiprivAttributedStringCopyUTF8ToUTF16Table(const uiAttributedString *s, size_t *n) +{ + size_t *out; + size_t nbytes; + + nbytes = (s->len + 1) * sizeof (size_t); + *n = s->len; + out = (size_t *) uiprivAlloc(nbytes, "size_t[] (uiAttributedString)"); + memmove(out, s->u8tou16, nbytes); + return out; +} + +size_t *uiprivAttributedStringCopyUTF16ToUTF8Table(const uiAttributedString *s, size_t *n) +{ + size_t *out; + size_t nbytes; + + nbytes = (s->u16len + 1) * sizeof (size_t); + *n = s->u16len; + out = (size_t *) uiprivAlloc(nbytes, "size_t[] (uiAttributedString)"); + memmove(out, s->u16tou8, nbytes); + return out; +} diff --git a/dep/libui/common/attrstr.h b/dep/libui/common/attrstr.h new file mode 100644 index 0000000..69ada5c --- /dev/null +++ b/dep/libui/common/attrstr.h @@ -0,0 +1,46 @@ +// 19 february 2018 + +#ifdef __cplusplus +extern "C" { +#endif + +// attribute.c +extern uiAttribute *uiprivAttributeRetain(uiAttribute *a); +extern void uiprivAttributeRelease(uiAttribute *a); +extern int uiprivAttributeEqual(const uiAttribute *a, const uiAttribute *b); + +// opentype.c +extern int uiprivOpenTypeFeaturesEqual(const uiOpenTypeFeatures *a, const uiOpenTypeFeatures *b); + +// attrlist.c +typedef struct uiprivAttrList uiprivAttrList; +extern uiprivAttrList *uiprivNewAttrList(void); +extern void uiprivFreeAttrList(uiprivAttrList *alist); +extern void uiprivAttrListInsertAttribute(uiprivAttrList *alist, uiAttribute *val, size_t start, size_t end); +extern void uiprivAttrListInsertCharactersUnattributed(uiprivAttrList *alist, size_t start, size_t count); +extern void uiprivAttrListInsertCharactersExtendingAttributes(uiprivAttrList *alist, size_t start, size_t count); +extern void uiprivAttrListRemoveAttribute(uiprivAttrList *alist, uiAttributeType type, size_t start, size_t end); +extern void uiprivAttrListRemoveAttributes(uiprivAttrList *alist, size_t start, size_t end); +extern void uiprivAttrListRemoveCharacters(uiprivAttrList *alist, size_t start, size_t end); +extern void uiprivAttrListForEach(const uiprivAttrList *alist, const uiAttributedString *s, uiAttributedStringForEachAttributeFunc f, void *data); + +// attrstr.c +extern const uint16_t *uiprivAttributedStringUTF16String(const uiAttributedString *s); +extern size_t uiprivAttributedStringUTF16Len(const uiAttributedString *s); +extern size_t uiprivAttributedStringUTF8ToUTF16(const uiAttributedString *s, size_t n); +extern size_t *uiprivAttributedStringCopyUTF8ToUTF16Table(const uiAttributedString *s, size_t *n); +extern size_t *uiprivAttributedStringCopyUTF16ToUTF8Table(const uiAttributedString *s, size_t *n); + +// per-OS graphemes.c/graphemes.cpp/graphemes.m/etc. +typedef struct uiprivGraphemes uiprivGraphemes; +struct uiprivGraphemes { + size_t len; + size_t *pointsToGraphemes; + size_t *graphemesToPoints; +}; +extern int uiprivGraphemesTakesUTF16(void); +extern uiprivGraphemes *uiprivNewGraphemes(void *s, size_t len); + +#ifdef __cplusplus +} +#endif diff --git a/dep/libui/common/control.c b/dep/libui/common/control.c new file mode 100644 index 0000000..98cb94a --- /dev/null +++ b/dep/libui/common/control.c @@ -0,0 +1,101 @@ +// 26 may 2015 +#include "../ui.h" +#include "uipriv.h" + +void uiControlDestroy(uiControl *c) +{ + (*(c->Destroy))(c); +} + +uintptr_t uiControlHandle(uiControl *c) +{ + return (*(c->Handle))(c); +} + +uiControl *uiControlParent(uiControl *c) +{ + return (*(c->Parent))(c); +} + +void uiControlSetParent(uiControl *c, uiControl *parent) +{ + (*(c->SetParent))(c, parent); +} + +int uiControlToplevel(uiControl *c) +{ + return (*(c->Toplevel))(c); +} + +int uiControlVisible(uiControl *c) +{ + return (*(c->Visible))(c); +} + +void uiControlShow(uiControl *c) +{ + (*(c->Show))(c); +} + +void uiControlHide(uiControl *c) +{ + (*(c->Hide))(c); +} + +int uiControlEnabled(uiControl *c) +{ + return (*(c->Enabled))(c); +} + +void uiControlEnable(uiControl *c) +{ + (*(c->Enable))(c); +} + +void uiControlDisable(uiControl *c) +{ + (*(c->Disable))(c); +} + +#define uiprivControlSignature 0x7569436F + +uiControl *uiAllocControl(size_t size, uint32_t OSsig, uint32_t typesig, const char *typenamestr) +{ + uiControl *c; + + c = (uiControl *) uiprivAlloc(size, typenamestr); + c->Signature = uiprivControlSignature; + c->OSSignature = OSsig; + c->TypeSignature = typesig; + return c; +} + +void uiFreeControl(uiControl *c) +{ + if (uiControlParent(c) != NULL) + uiprivUserBug("You cannot destroy a uiControl while it still has a parent. (control: %p)", c); + uiprivFree(c); +} + +void uiControlVerifySetParent(uiControl *c, uiControl *parent) +{ + uiControl *curParent; + + if (uiControlToplevel(c)) + uiprivUserBug("You cannot give a toplevel uiControl a parent. (control: %p)", c); + curParent = uiControlParent(c); + if (parent != NULL && curParent != NULL) + uiprivUserBug("You cannot give a uiControl a parent while it already has one. (control: %p; current parent: %p; new parent: %p)", c, curParent, parent); + if (parent == NULL && curParent == NULL) + uiprivImplBug("attempt to double unparent uiControl %p", c); +} + +int uiControlEnabledToUser(uiControl *c) +{ + while (c != NULL) { + if (!uiControlEnabled(c)) + return 0; + c = uiControlParent(c); + } + return 1; +} diff --git a/dep/libui/common/controlsigs.h b/dep/libui/common/controlsigs.h new file mode 100644 index 0000000..944afa9 --- /dev/null +++ b/dep/libui/common/controlsigs.h @@ -0,0 +1,27 @@ +// 24 april 2016 + +// LONGTERM if I don't decide to remove these outright, should they be renamed uiprivTypeNameSignature? these aren't real symbols, so... + +#define uiAreaSignature 0x41726561 +#define uiBoxSignature 0x426F784C +#define uiButtonSignature 0x42746F6E +#define uiCheckboxSignature 0x43686B62 +#define uiColorButtonSignature 0x436F6C42 +#define uiComboboxSignature 0x436F6D62 +#define uiDateTimePickerSignature 0x44545069 +#define uiEditableComboboxSignature 0x45644362 +#define uiEntrySignature 0x456E7472 +#define uiFontButtonSignature 0x466F6E42 +#define uiFormSignature 0x466F726D +#define uiGridSignature 0x47726964 +#define uiGroupSignature 0x47727062 +#define uiLabelSignature 0x4C61626C +#define uiMultilineEntrySignature 0x4D6C6E45 +#define uiProgressBarSignature 0x50426172 +#define uiRadioButtonsSignature 0x5264696F +#define uiSeparatorSignature 0x53657061 +#define uiSliderSignature 0x536C6964 +#define uiSpinboxSignature 0x5370696E +#define uiTabSignature 0x54616273 +#define uiTableSignature 0x5461626C +#define uiWindowSignature 0x57696E64 diff --git a/dep/libui/common/debug.c b/dep/libui/common/debug.c new file mode 100644 index 0000000..aa24e29 --- /dev/null +++ b/dep/libui/common/debug.c @@ -0,0 +1,21 @@ +// 13 may 2016 +#include "../ui.h" +#include "uipriv.h" + +void uiprivDoImplBug(const char *file, const char *line, const char *func, const char *format, ...) +{ + va_list ap; + + va_start(ap, format); + uiprivRealBug(file, line, func, "POSSIBLE IMPLEMENTATION BUG; CONTACT ANDLABS:\n", format, ap); + va_end(ap); +} + +void uiprivDoUserBug(const char *file, const char *line, const char *func, const char *format, ...) +{ + va_list ap; + + va_start(ap, format); + uiprivRealBug(file, line, func, "You have a bug: ", format, ap); + va_end(ap); +} diff --git a/dep/libui/common/matrix.c b/dep/libui/common/matrix.c new file mode 100644 index 0000000..93d4d35 --- /dev/null +++ b/dep/libui/common/matrix.c @@ -0,0 +1,50 @@ +// 11 october 2015 +#include +#include "../ui.h" +#include "uipriv.h" + +void uiDrawMatrixSetIdentity(uiDrawMatrix *m) +{ + m->M11 = 1; + m->M12 = 0; + m->M21 = 0; + m->M22 = 1; + m->M31 = 0; + m->M32 = 0; +} + +// The rest of this file provides basic utilities in case the platform doesn't provide any of its own for these tasks. +// Keep these as minimal as possible. They should generally not call other fallbacks. + +// see https://msdn.microsoft.com/en-us/library/windows/desktop/ff684171%28v=vs.85%29.aspx#skew_transform +// TODO see if there's a way we can avoid the multiplication +void uiprivFallbackSkew(uiDrawMatrix *m, double x, double y, double xamount, double yamount) +{ + uiDrawMatrix n; + + uiDrawMatrixSetIdentity(&n); + // TODO explain this + n.M12 = tan(yamount); + n.M21 = tan(xamount); + n.M31 = -y * tan(xamount); + n.M32 = -x * tan(yamount); + uiDrawMatrixMultiply(m, &n); +} + +void uiprivScaleCenter(double xCenter, double yCenter, double *x, double *y) +{ + *x = xCenter - (*x * xCenter); + *y = yCenter - (*y * yCenter); +} + +// the basic algorithm is from cairo +// but it's the same algorithm as the transform point, just without M31 and M32 taken into account, so let's just do that instead +void uiprivFallbackTransformSize(uiDrawMatrix *m, double *x, double *y) +{ + uiDrawMatrix m2; + + m2 = *m; + m2.M31 = 0; + m2.M32 = 0; + uiDrawMatrixTransformPoint(&m2, x, y); +} diff --git a/dep/libui/common/meson.build b/dep/libui/common/meson.build new file mode 100644 index 0000000..3146add --- /dev/null +++ b/dep/libui/common/meson.build @@ -0,0 +1,17 @@ +# 23 march 2019 + +libui_sources += [ + 'common/attribute.c', + 'common/attrlist.c', + 'common/attrstr.c', + 'common/areaevents.c', + 'common/control.c', + 'common/debug.c', + 'common/matrix.c', + 'common/opentype.c', + 'common/shouldquit.c', + 'common/tablemodel.c', + 'common/tablevalue.c', + 'common/userbugs.c', + 'common/utf.c', +] diff --git a/dep/libui/common/opentype.c b/dep/libui/common/opentype.c new file mode 100644 index 0000000..e579b61 --- /dev/null +++ b/dep/libui/common/opentype.c @@ -0,0 +1,165 @@ +// 25 february 2018 +#include +#include "../ui.h" +#include "uipriv.h" +#include "attrstr.h" + +struct feature { + char a; + char b; + char c; + char d; + uint32_t value; +}; + +struct uiOpenTypeFeatures { + struct feature *data; + size_t len; + size_t cap; +}; + +#define bytecount(n) ((n) * sizeof (struct feature)) + +uiOpenTypeFeatures *uiNewOpenTypeFeatures(void) +{ + uiOpenTypeFeatures *otf; + + otf = uiprivNew(uiOpenTypeFeatures); + otf->cap = 16; + otf->data = (struct feature *) uiprivAlloc(bytecount(otf->cap), "struct feature[]"); + otf->len = 0; + return otf; +} + +void uiFreeOpenTypeFeatures(uiOpenTypeFeatures *otf) +{ + uiprivFree(otf->data); + uiprivFree(otf); +} + +uiOpenTypeFeatures *uiOpenTypeFeaturesClone(const uiOpenTypeFeatures *otf) +{ + uiOpenTypeFeatures *ret; + + ret = uiprivNew(uiOpenTypeFeatures); + ret->len = otf->len; + ret->cap = otf->cap; + ret->data = (struct feature *) uiprivAlloc(bytecount(ret->cap), "struct feature[]"); + memset(ret->data, 0, bytecount(ret->cap)); + memmove(ret->data, otf->data, bytecount(ret->len)); + return ret; +} + +#define intdiff(a, b) (((int) (a)) - ((int) (b))) + +static int featurecmp(const void *a, const void *b) +{ + const struct feature *f = (const struct feature *) a; + const struct feature *g = (const struct feature *) b; + + if (f->a != g->a) + return intdiff(f->a, g->a); + if (f->b != g->b) + return intdiff(f->b, g->b); + if (f->c != g->c) + return intdiff(f->c, g->c); + return intdiff(f->d, g->d); +} + +static struct feature mkkey(char a, char b, char c, char d) +{ + struct feature f; + + f.a = a; + f.b = b; + f.c = c; + f.d = d; + return f; +} + +#define find(pkey, otf) bsearch(pkey, otf->data, otf->len, sizeof (struct feature), featurecmp) + +void uiOpenTypeFeaturesAdd(uiOpenTypeFeatures *otf, char a, char b, char c, char d, uint32_t value) +{ + struct feature *f; + struct feature key; + + // replace existing value if any + key = mkkey(a, b, c, d); + f = (struct feature *) find(&key, otf); + if (f != NULL) { + f->value = value; + return; + } + + // if we got here, the tag is new + if (otf->len == otf->cap) { + otf->cap *= 2; + otf->data = (struct feature *) uiprivRealloc(otf->data, bytecount(otf->cap), "struct feature[]"); + } + f = otf->data + otf->len; + f->a = a; + f->b = b; + f->c = c; + f->d = d; + f->value = value; + // LONGTERM qsort here is overkill + otf->len++; + qsort(otf->data, otf->len, sizeof (struct feature), featurecmp); +} + +void uiOpenTypeFeaturesRemove(uiOpenTypeFeatures *otf, char a, char b, char c, char d) +{ + struct feature *f; + struct feature key; + ptrdiff_t index; + size_t count; + + key = mkkey(a, b, c, d); + f = (struct feature *) find(&key, otf); + if (f == NULL) + return; + + index = f - otf->data; + count = otf->len - index - 1; + memmove(f + 1, f, bytecount(count)); + otf->len--; +} + +int uiOpenTypeFeaturesGet(const uiOpenTypeFeatures *otf, char a, char b, char c, char d, uint32_t *value) +{ + const struct feature *f; + struct feature key; + + key = mkkey(a, b, c, d); + f = (const struct feature *) find(&key, otf); + if (f == NULL) + return 0; + *value = f->value; + return 1; +} + +void uiOpenTypeFeaturesForEach(const uiOpenTypeFeatures *otf, uiOpenTypeFeaturesForEachFunc f, void *data) +{ + size_t n; + const struct feature *p; + uiForEach ret; + + p = otf->data; + for (n = 0; n < otf->len; n++) { + ret = (*f)(otf, p->a, p->b, p->c, p->d, p->value, data); + // TODO for all: require exact match? + if (ret == uiForEachStop) + return; + p++; + } +} + +int uiprivOpenTypeFeaturesEqual(const uiOpenTypeFeatures *a, const uiOpenTypeFeatures *b) +{ + if (a == b) + return 1; + if (a->len != b->len) + return 0; + return memcmp(a->data, b->data, bytecount(a->len)) == 0; +} diff --git a/dep/libui/common/shouldquit.c b/dep/libui/common/shouldquit.c new file mode 100644 index 0000000..df57b6c --- /dev/null +++ b/dep/libui/common/shouldquit.c @@ -0,0 +1,22 @@ +// 9 may 2015 +#include "../ui.h" +#include "uipriv.h" + +static int defaultOnShouldQuit(void *data) +{ + return 0; +} + +static int (*onShouldQuit)(void *) = defaultOnShouldQuit; +static void *onShouldQuitData = NULL; + +void uiOnShouldQuit(int (*f)(void *), void *data) +{ + onShouldQuit = f; + onShouldQuitData = data; +} + +int uiprivShouldQuit(void) +{ + return (*onShouldQuit)(onShouldQuitData); +} diff --git a/dep/libui/common/table.h b/dep/libui/common/table.h new file mode 100644 index 0000000..f83205d --- /dev/null +++ b/dep/libui/common/table.h @@ -0,0 +1,20 @@ +// 23 june 2018 + +#ifdef __cplusplus +extern "C" { +#endif + +// tablemodel.c +extern uiTableModelHandler *uiprivTableModelHandler(uiTableModel *m); +extern int uiprivTableModelNumColumns(uiTableModel *m); +extern uiTableValueType uiprivTableModelColumnType(uiTableModel *m, int column); +extern int uiprivTableModelNumRows(uiTableModel *m); +extern uiTableValue *uiprivTableModelCellValue(uiTableModel *m, int row, int column); +extern void uiprivTableModelSetCellValue(uiTableModel *m, int row, int column, const uiTableValue *value); +extern const uiTableTextColumnOptionalParams uiprivDefaultTextColumnOptionalParams; +extern int uiprivTableModelCellEditable(uiTableModel *m, int row, int column); +extern int uiprivTableModelColorIfProvided(uiTableModel *m, int row, int column, double *r, double *g, double *b, double *a); + +#ifdef __cplusplus +} +#endif diff --git a/dep/libui/common/tablemodel.c b/dep/libui/common/tablemodel.c new file mode 100644 index 0000000..dbda4a8 --- /dev/null +++ b/dep/libui/common/tablemodel.c @@ -0,0 +1,79 @@ +// 23 june 2018 +#include "../ui.h" +#include "uipriv.h" +#include "table.h" + +int uiprivTableModelNumColumns(uiTableModel *m) +{ + uiTableModelHandler *mh; + + mh = uiprivTableModelHandler(m); + return (*(mh->NumColumns))(mh, m); +} + +uiTableValueType uiprivTableModelColumnType(uiTableModel *m, int column) +{ + uiTableModelHandler *mh; + + mh = uiprivTableModelHandler(m); + return (*(mh->ColumnType))(mh, m, column); +} + +int uiprivTableModelNumRows(uiTableModel *m) +{ + uiTableModelHandler *mh; + + mh = uiprivTableModelHandler(m); + return (*(mh->NumRows))(mh, m); +} + +uiTableValue *uiprivTableModelCellValue(uiTableModel *m, int row, int column) +{ + uiTableModelHandler *mh; + + mh = uiprivTableModelHandler(m); + return (*(mh->CellValue))(mh, m, row, column); +} + +void uiprivTableModelSetCellValue(uiTableModel *m, int row, int column, const uiTableValue *value) +{ + uiTableModelHandler *mh; + + mh = uiprivTableModelHandler(m); + (*(mh->SetCellValue))(mh, m, row, column, value); +} + +const uiTableTextColumnOptionalParams uiprivDefaultTextColumnOptionalParams = { + .ColorModelColumn = -1, +}; + +int uiprivTableModelCellEditable(uiTableModel *m, int row, int column) +{ + uiTableValue *value; + int editable; + + switch (column) { + case uiTableModelColumnNeverEditable: + return 0; + case uiTableModelColumnAlwaysEditable: + return 1; + } + value = uiprivTableModelCellValue(m, row, column); + editable = uiTableValueInt(value); + uiFreeTableValue(value); + return editable; +} + +int uiprivTableModelColorIfProvided(uiTableModel *m, int row, int column, double *r, double *g, double *b, double *a) +{ + uiTableValue *value; + + if (column == -1) + return 0; + value = uiprivTableModelCellValue(m, row, column); + if (value == NULL) + return 0; + uiTableValueColor(value, r, g, b, a); + uiFreeTableValue(value); + return 1; +} diff --git a/dep/libui/common/tablevalue.c b/dep/libui/common/tablevalue.c new file mode 100644 index 0000000..10043de --- /dev/null +++ b/dep/libui/common/tablevalue.c @@ -0,0 +1,106 @@ +// 3 june 2018 +#include "../ui.h" +#include "uipriv.h" +#include "table.h" + +struct uiTableValue { + uiTableValueType type; + union { + char *str; + uiImage *img; + int i; + struct { + double r; + double g; + double b; + double a; + } color; + } u; +}; + +static uiTableValue *newTableValue(uiTableValueType type) +{ + uiTableValue *v; + + v = uiprivNew(uiTableValue); + v->type = type; + return v; +} + +void uiFreeTableValue(uiTableValue *v) +{ + switch (v->type) { + case uiTableValueTypeString: + uiprivFree(v->u.str); + break; + } + uiprivFree(v); +} + +uiTableValueType uiTableValueGetType(const uiTableValue *v) +{ + return v->type; +} + +uiTableValue *uiNewTableValueString(const char *str) +{ + uiTableValue *v; + + v = newTableValue(uiTableValueTypeString); + v->u.str = (char *) uiprivAlloc((strlen(str) + 1) * sizeof (char), "char[] (uiTableValue)"); + strcpy(v->u.str, str); + return v; +} + +const char *uiTableValueString(const uiTableValue *v) +{ + return v->u.str; +} + +uiTableValue *uiNewTableValueImage(uiImage *img) +{ + uiTableValue *v; + + v = newTableValue(uiTableValueTypeImage); + v->u.img = img; + return v; +} + +uiImage *uiTableValueImage(const uiTableValue *v) +{ + return v->u.img; +} + +uiTableValue *uiNewTableValueInt(int i) +{ + uiTableValue *v; + + v = newTableValue(uiTableValueTypeInt); + v->u.i = i; + return v; +} + +int uiTableValueInt(const uiTableValue *v) +{ + return v->u.i; +} + +uiTableValue *uiNewTableValueColor(double r, double g, double b, double a) +{ + uiTableValue *v; + + v = newTableValue(uiTableValueTypeColor); + v->u.color.r = r; + v->u.color.g = g; + v->u.color.b = b; + v->u.color.a = a; + return v; +} + +void uiTableValueColor(const uiTableValue *v, double *r, double *g, double *b, double *a) +{ + *r = v->u.color.r; + *g = v->u.color.g; + *b = v->u.color.b; + *a = v->u.color.a; +} diff --git a/dep/libui/common/uipriv.h b/dep/libui/common/uipriv.h new file mode 100644 index 0000000..6441ada --- /dev/null +++ b/dep/libui/common/uipriv.h @@ -0,0 +1,67 @@ +// 6 april 2015 +// note: this file should not include ui.h, as the OS-specific ui_*.h files are included between that one and this one in the OS-specific uipriv_*.h* files +#include +#include +#include "controlsigs.h" +#include "utf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// OS-specific init.* or main.* files +extern uiInitOptions uiprivOptions; + +// OS-specific alloc.* files +extern void *uiprivAlloc(size_t, const char *); +#define uiprivNew(T) ((T *) uiprivAlloc(sizeof (T), #T)) +extern void *uiprivRealloc(void *, size_t, const char *); +extern void uiprivFree(void *); + +// debug.c and OS-specific debug.* files +// TODO get rid of this mess... +// ugh, __func__ was only introduced in MSVC 2015... +#ifdef _MSC_VER +#define uiprivMacro__func__ __FUNCTION__ +#else +#define uiprivMacro__func__ __func__ +#endif +extern void uiprivRealBug(const char *file, const char *line, const char *func, const char *prefix, const char *format, va_list ap); +#define uiprivMacro_ns2(s) #s +#define uiprivMacro_ns(s) uiprivMacro_ns2(s) +extern void uiprivDoImplBug(const char *file, const char *line, const char *func, const char *format, ...); +#define uiprivImplBug(...) uiprivDoImplBug(__FILE__, uiprivMacro_ns(__LINE__), uiprivMacro__func__, __VA_ARGS__) +extern void uiprivDoUserBug(const char *file, const char *line, const char *func, const char *format, ...); +#define uiprivUserBug(...) uiprivDoUserBug(__FILE__, uiprivMacro_ns(__LINE__), uiprivMacro__func__, __VA_ARGS__) + +// shouldquit.c +extern int uiprivShouldQuit(void); + +// areaevents.c +typedef struct uiprivClickCounter uiprivClickCounter; +// you should call Reset() to zero-initialize a new instance +// it doesn't matter that all the non-count fields are zero: the first click will fail the curButton test straightaway, so it'll return 1 and set the rest of the structure accordingly +struct uiprivClickCounter { + int curButton; + int rectX0; + int rectY0; + int rectX1; + int rectY1; + uintptr_t prevTime; + int count; +}; +extern int uiprivClickCounterClick(uiprivClickCounter *c, int button, int x, int y, uintptr_t time, uintptr_t maxTime, int32_t xdist, int32_t ydist); +extern void uiprivClickCounterReset(uiprivClickCounter *); +extern int uiprivFromScancode(uintptr_t, uiAreaKeyEvent *); + +// matrix.c +extern void uiprivFallbackSkew(uiDrawMatrix *, double, double, double, double); +extern void uiprivScaleCenter(double, double, double *, double *); +extern void uiprivFallbackTransformSize(uiDrawMatrix *, double *, double *); + +// OS-specific text.* files +extern int uiprivStricmp(const char *a, const char *b); + +#ifdef __cplusplus +} +#endif diff --git a/dep/libui/common/userbugs.c b/dep/libui/common/userbugs.c new file mode 100644 index 0000000..09cc703 --- /dev/null +++ b/dep/libui/common/userbugs.c @@ -0,0 +1,8 @@ +// 22 may 2016 +#include "../ui.h" +#include "uipriv.h" + +void uiUserBugCannotSetParentOnToplevel(const char *type) +{ + uiprivUserBug("You cannot make a %s a child of another uiControl,", type); +} diff --git a/dep/libui/common/utf.c b/dep/libui/common/utf.c new file mode 100644 index 0000000..5577529 --- /dev/null +++ b/dep/libui/common/utf.c @@ -0,0 +1,348 @@ +// utf by pietro gagliardi (andlabs) — https://github.com/andlabs/utf/ +// 10 november 2016 +// function names have been altered to avoid namespace collisions in libui static builds (see utf.h) +#include "utf.h" + +// this code imitates Go's unicode/utf8 and unicode/utf16 +// the biggest difference is that a rune is unsigned instead of signed (because Go guarantees what a right shift on a signed number will do, whereas C does not) +// it is also an imitation so we can license it under looser terms than the Go source +#define badrune 0xFFFD + +// encoded must be at most 4 bytes +// TODO clean this code up somehow +size_t uiprivUTF8EncodeRune(uint32_t rune, char *encoded) +{ + uint8_t b, c, d, e; + size_t n; + + // not in the valid range for Unicode + if (rune > 0x10FFFF) + rune = badrune; + // surrogate runes cannot be encoded + if (rune >= 0xD800 && rune < 0xE000) + rune = badrune; + + if (rune < 0x80) { // ASCII bytes represent themselves + b = (uint8_t) (rune & 0xFF); + n = 1; + goto done; + } + if (rune < 0x800) { // two-byte encoding + c = (uint8_t) (rune & 0x3F); + c |= 0x80; + rune >>= 6; + b = (uint8_t) (rune & 0x1F); + b |= 0xC0; + n = 2; + goto done; + } + if (rune < 0x10000) { // three-byte encoding + d = (uint8_t) (rune & 0x3F); + d |= 0x80; + rune >>= 6; + c = (uint8_t) (rune & 0x3F); + c |= 0x80; + rune >>= 6; + b = (uint8_t) (rune & 0x0F); + b |= 0xE0; + n = 3; + goto done; + } + // otherwise use a four-byte encoding + e = (uint8_t) (rune & 0x3F); + e |= 0x80; + rune >>= 6; + d = (uint8_t) (rune & 0x3F); + d |= 0x80; + rune >>= 6; + c = (uint8_t) (rune & 0x3F); + c |= 0x80; + rune >>= 6; + b = (uint8_t) (rune & 0x07); + b |= 0xF0; + n = 4; + +done: + encoded[0] = b; + if (n > 1) + encoded[1] = c; + if (n > 2) + encoded[2] = d; + if (n > 3) + encoded[3] = e; + return n; +} + +const char *uiprivUTF8DecodeRune(const char *s, size_t nElem, uint32_t *rune) +{ + uint8_t b, c; + uint8_t lowestAllowed, highestAllowed; + size_t i, expected; + int bad; + + b = (uint8_t) (*s); + if (b < 0x80) { // ASCII bytes represent themselves + *rune = b; + s++; + return s; + } + // 0xC0 and 0xC1 cover 2-byte overlong equivalents + // 0xF5 to 0xFD cover values > 0x10FFFF + // 0xFE and 0xFF were never defined (always illegal) + if (b < 0xC2 || b > 0xF4) { // invalid + *rune = badrune; + s++; + return s; + } + + // this determines the range of allowed first continuation bytes + lowestAllowed = 0x80; + highestAllowed = 0xBF; + switch (b) { + case 0xE0: + // disallow 3-byte overlong equivalents + lowestAllowed = 0xA0; + break; + case 0xED: + // disallow surrogate characters + highestAllowed = 0x9F; + break; + case 0xF0: + // disallow 4-byte overlong equivalents + lowestAllowed = 0x90; + break; + case 0xF4: + // disallow values > 0x10FFFF + highestAllowed = 0x8F; + break; + } + + // and this determines how many continuation bytes are expected + expected = 1; + if (b >= 0xE0) + expected++; + if (b >= 0xF0) + expected++; + if (nElem != 0) { // are there enough bytes? + nElem--; + if (nElem < expected) { // nope + *rune = badrune; + s++; + return s; + } + } + + // ensure that everything is correct + // if not, **only** consume the initial byte + bad = 0; + for (i = 0; i < expected; i++) { + c = (uint8_t) (s[1 + i]); + if (c < lowestAllowed || c > highestAllowed) { + bad = 1; + break; + } + // the old lowestAllowed and highestAllowed is only for the first continuation byte + lowestAllowed = 0x80; + highestAllowed = 0xBF; + } + if (bad) { + *rune = badrune; + s++; + return s; + } + + // now do the topmost bits + if (b < 0xE0) + *rune = b & 0x1F; + else if (b < 0xF0) + *rune = b & 0x0F; + else + *rune = b & 0x07; + s++; // we can finally move on + + // now do the continuation bytes + for (; expected; expected--) { + c = (uint8_t) (*s); + s++; + c &= 0x3F; // strip continuation bits + *rune <<= 6; + *rune |= c; + } + + return s; +} + +// encoded must have at most 2 elements +size_t uiprivUTF16EncodeRune(uint32_t rune, uint16_t *encoded) +{ + uint16_t low, high; + + // not in the valid range for Unicode + if (rune > 0x10FFFF) + rune = badrune; + // surrogate runes cannot be encoded + if (rune >= 0xD800 && rune < 0xE000) + rune = badrune; + + if (rune < 0x10000) { + encoded[0] = (uint16_t) rune; + return 1; + } + + rune -= 0x10000; + low = (uint16_t) (rune & 0x3FF); + rune >>= 10; + high = (uint16_t) (rune & 0x3FF); + encoded[0] = high | 0xD800; + encoded[1] = low | 0xDC00; + return 2; +} + +// TODO see if this can be cleaned up somehow +const uint16_t *uiprivUTF16DecodeRune(const uint16_t *s, size_t nElem, uint32_t *rune) +{ + uint16_t high, low; + + if (*s < 0xD800 || *s >= 0xE000) { + // self-representing character + *rune = *s; + s++; + return s; + } + if (*s >= 0xDC00) { + // out-of-order surrogates + *rune = badrune; + s++; + return s; + } + if (nElem == 1) { // not enough elements + *rune = badrune; + s++; + return s; + } + high = *s; + high &= 0x3FF; + if (s[1] < 0xDC00 || s[1] >= 0xE000) { + // bad surrogate pair + *rune = badrune; + s++; + return s; + } + s++; + low = *s; + s++; + low &= 0x3FF; + *rune = high; + *rune <<= 10; + *rune |= low; + *rune += 0x10000; + return s; +} + +// TODO find a way to reduce the code in all of these somehow +// TODO find a way to remove u as well +size_t uiprivUTF8RuneCount(const char *s, size_t nElem) +{ + size_t len; + uint32_t rune; + + if (nElem != 0) { + const char *t, *u; + + len = 0; + t = s; + while (nElem != 0) { + u = uiprivUTF8DecodeRune(t, nElem, &rune); + len++; + nElem -= u - t; + t = u; + } + return len; + } + len = 0; + while (*s) { + s = uiprivUTF8DecodeRune(s, nElem, &rune); + len++; + } + return len; +} + +size_t uiprivUTF8UTF16Count(const char *s, size_t nElem) +{ + size_t len; + uint32_t rune; + uint16_t encoded[2]; + + if (nElem != 0) { + const char *t, *u; + + len = 0; + t = s; + while (nElem != 0) { + u = uiprivUTF8DecodeRune(t, nElem, &rune); + len += uiprivUTF16EncodeRune(rune, encoded); + nElem -= u - t; + t = u; + } + return len; + } + len = 0; + while (*s) { + s = uiprivUTF8DecodeRune(s, nElem, &rune); + len += uiprivUTF16EncodeRune(rune, encoded); + } + return len; +} + +size_t uiprivUTF16RuneCount(const uint16_t *s, size_t nElem) +{ + size_t len; + uint32_t rune; + + if (nElem != 0) { + const uint16_t *t, *u; + + len = 0; + t = s; + while (nElem != 0) { + u = uiprivUTF16DecodeRune(t, nElem, &rune); + len++; + nElem -= u - t; + t = u; + } + return len; + } + len = 0; + while (*s) { + s = uiprivUTF16DecodeRune(s, nElem, &rune); + len++; + } + return len; +} + +size_t uiprivUTF16UTF8Count(const uint16_t *s, size_t nElem) +{ + size_t len; + uint32_t rune; + char encoded[4]; + + if (nElem != 0) { + const uint16_t *t, *u; + + len = 0; + t = s; + while (nElem != 0) { + u = uiprivUTF16DecodeRune(t, nElem, &rune); + len += uiprivUTF8EncodeRune(rune, encoded); + nElem -= u - t; + t = u; + } + return len; + } + len = 0; + while (*s) { + s = uiprivUTF16DecodeRune(s, nElem, &rune); + len += uiprivUTF8EncodeRune(rune, encoded); + } + return len; +} diff --git a/dep/libui/common/utf.h b/dep/libui/common/utf.h new file mode 100644 index 0000000..eafcea0 --- /dev/null +++ b/dep/libui/common/utf.h @@ -0,0 +1,105 @@ +// utf by pietro gagliardi (andlabs) — https://github.com/andlabs/utf/ +// 10 november 2016 + +// note the overridden names with uipriv at the beginning; this avoids potential symbol clashes when building libui as a static library +// LONGTERM find a way to encode the name overrides directly into the utf library + +#ifdef __cplusplus +extern "C" { +#endif + +// TODO (for utf itself as well) should this go outside the extern "C" block or not +#include +#include + +// if nElem == 0, assume the buffer has no upper limit and is '\0' terminated +// otherwise, assume buffer is NOT '\0' terminated but is bounded by nElem *elements* + +extern size_t uiprivUTF8EncodeRune(uint32_t rune, char *encoded); +extern const char *uiprivUTF8DecodeRune(const char *s, size_t nElem, uint32_t *rune); +extern size_t uiprivUTF16EncodeRune(uint32_t rune, uint16_t *encoded); +extern const uint16_t *uiprivUTF16DecodeRune(const uint16_t *s, size_t nElem, uint32_t *rune); + +extern size_t uiprivUTF8RuneCount(const char *s, size_t nElem); +extern size_t uiprivUTF8UTF16Count(const char *s, size_t nElem); +extern size_t uiprivUTF16RuneCount(const uint16_t *s, size_t nElem); +extern size_t uiprivUTF16UTF8Count(const uint16_t *s, size_t nElem); + +#ifdef __cplusplus +} + +// TODO sync this back to upstream (need copyright clearance first) + +// On Windows, wchar_t is equivalent to uint16_t, but C++ requires +// wchar_t to be a completely distinct type. These overloads allow +// passing wchar_t pointers directly into these functions from C++ +// on Windows. Otherwise, you'd need to cast to pass a wchar_t +// pointer, WCHAR pointer, or equivalent to these functions. +// +// This does not apply to MSVC because the situation there is +// slightly more complicated; see below. +#if defined(_WIN32) && !defined(_MSC_VER) + +inline size_t uiprivUTF16EncodeRune(uint32_t rune, wchar_t *encoded) +{ + return uiprivUTF16EncodeRune(rune, reinterpret_cast(encoded)); +} + +inline const wchar_t *uiprivUTF16DecodeRune(const wchar_t *s, size_t nElem, uint32_t *rune) +{ + const uint16_t *ret; + + ret = uiprivUTF16DecodeRune(reinterpret_cast(s), nElem, rune); + return reinterpret_cast(ret); +} + +inline size_t uiprivUTF16RuneCount(const wchar_t *s, size_t nElem) +{ + return uiprivUTF16RuneCount(reinterpret_cast(s), nElem); +} + +inline size_t uiprivUTF16UTF8Count(const wchar_t *s, size_t nElem) +{ + return uiprivUTF16UTF8Count(reinterpret_cast(s), nElem); +} + +#endif + +// This is the same as the above, except that with MSVC, whether +// wchar_t is a keyword or not is controlled by a compiler option! +// (At least with gcc, this is not the case; thanks redi in +// irc.freenode.net/#gcc.) We use __wchar_t to be independent of +// the option; see https://blogs.msdn.microsoft.com/oldnewthing/20161201-00/?p=94836 +// (ironically posted one day after I initially wrote this code!). +// TODO should defined(_WIN32) be used too? +// TODO check this under /Wall +// TODO are C-style casts enough? or will that fail in /Wall? +// TODO same for UniChar/unichar on Mac? if both are unsigned then we have nothing to worry about +#if defined(_MSC_VER) + +inline size_t uiprivUTF16EncodeRune(uint32_t rune, __wchar_t *encoded) +{ + return uiprivUTF16EncodeRune(rune, reinterpret_cast(encoded)); +} + +inline const __wchar_t *uiprivUTF16DecodeRune(const __wchar_t *s, size_t nElem, uint32_t *rune) +{ + const uint16_t *ret; + + ret = uiprivUTF16DecodeRune(reinterpret_cast(s), nElem, rune); + return reinterpret_cast(ret); +} + +inline size_t uiprivUTF16RuneCount(const __wchar_t *s, size_t nElem) +{ + return uiprivUTF16RuneCount(reinterpret_cast(s), nElem); +} + +inline size_t uiprivUTF16UTF8Count(const __wchar_t *s, size_t nElem) +{ + return uiprivUTF16UTF8Count(reinterpret_cast(s), nElem); +} + +#endif + +#endif diff --git a/dep/libui/darwin/OLD_table.m b/dep/libui/darwin/OLD_table.m new file mode 100644 index 0000000..18231f5 --- /dev/null +++ b/dep/libui/darwin/OLD_table.m @@ -0,0 +1,39 @@ +// 21 june 2016 +#import "uipriv_darwin.h" + +// TODOs +// - header cell seems off +// - background color shows up for a line or two below selection +// - editable NSTextFields have no intrinsic width +// - is the Y position of checkbox cells correct? + +@implementation tablePart + +- (NSView *)mkView:(uiTableModel *)m row:(int)row +{ + // if stretchy, don't hug, otherwise hug forcibly + if (self.expand) + [view setContentHuggingPriority:NSLayoutPriorityDefaultLow forOrientation:NSLayoutConstraintOrientationHorizontal]; + else + [view setContentHuggingPriority:NSLayoutPriorityRequired forOrientation:NSLayoutConstraintOrientationHorizontal]; +} + +@end + +uiTableColumn *uiTableAppendColumn(uiTable *t, const char *name) +{ + uiTableColumn *c; + + c = uiprivNew(uiTableColumn); + c->c = [[tableColumn alloc] initWithIdentifier:@""]; + c->c.libui_col = c; + // via Interface Builder + [c->c setResizingMask:(NSTableColumnAutoresizingMask | NSTableColumnUserResizingMask)]; + // 10.10 adds -[NSTableColumn setTitle:]; before then we have to do this + [[c->c headerCell] setStringValue:uiprivToNSString(name)]; + // TODO is this sufficient? + [[c->c headerCell] setFont:[NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:NSSmallControlSize]]]; + c->parts = [NSMutableArray new]; + [t->tv addTableColumn:c->c]; + return c; +} diff --git a/dep/libui/darwin/aat.m b/dep/libui/darwin/aat.m new file mode 100644 index 0000000..05f0b26 --- /dev/null +++ b/dep/libui/darwin/aat.m @@ -0,0 +1,403 @@ +// 14 february 2017 +#import "uipriv_darwin.h" +#import "attrstr.h" + +// TODO explain the purpose of this file + +static void boolspec(uint32_t value, uint16_t type, uint16_t ifTrue, uint16_t ifFalse, uiprivAATBlock f) +{ + // TODO are values other than 1 accepted for true by OpenType itself? (same for the rest of the file) + if (value != 0) { + f(type, ifTrue); + return; + } + f(type, ifFalse); +} + +// TODO remove the need for this +// TODO remove x8tox32() +#define x8tox32(x) ((uint32_t) (((uint8_t) (x)) & 0xFF)) +#define mkTag(a, b, c, d) \ + ((x8tox32(a) << 24) | \ + (x8tox32(b) << 16) | \ + (x8tox32(c) << 8) | \ + x8tox32(d)) + +// TODO double-check drawtext example to make sure all of these are used properly (I already screwed dlig up by putting clig twice instead) +void uiprivOpenTypeToAAT(char a, char b, char c, char d, uint32_t value, uiprivAATBlock f) +{ + switch (mkTag(a, b, c, d)) { + case mkTag('l', 'i', 'g', 'a'): + boolspec(value, kLigaturesType, + kCommonLigaturesOnSelector, + kCommonLigaturesOffSelector, + f); + break; + case mkTag('r', 'l', 'i', 'g'): + boolspec(value, kLigaturesType, + kRequiredLigaturesOnSelector, + kRequiredLigaturesOffSelector, + f); + break; + case mkTag('d', 'l', 'i', 'g'): + boolspec(value, kLigaturesType, + kRareLigaturesOnSelector, + kRareLigaturesOffSelector, + f); + break; + case mkTag('c', 'l', 'i', 'g'): + boolspec(value, kLigaturesType, + kContextualLigaturesOnSelector, + kContextualLigaturesOffSelector, + f); + break; + case mkTag('h', 'l', 'i', 'g'): + // This technically isn't what is meant by "historical ligatures", but Core Text's internal AAT-to-OpenType mapping says to include it, so we include it too + case mkTag('h', 'i', 's', 't'): + boolspec(value, kLigaturesType, + kHistoricalLigaturesOnSelector, + kHistoricalLigaturesOffSelector, + f); + break; + case mkTag('u', 'n', 'i', 'c'): + // TODO is this correct, or should we provide an else case? + if (value != 0) + // this is undocumented; it comes from Core Text's internal AAT-to-OpenType conversion table + f(kLetterCaseType, 14); + break; + + // TODO will the following handle all cases properly, or are elses going to be needed? + case mkTag('p', 'n', 'u', 'm'): + if (value != 0) + f(kNumberSpacingType, kProportionalNumbersSelector); + break; + case mkTag('t', 'n', 'u', 'm'): + if (value != 0) + f(kNumberSpacingType, kMonospacedNumbersSelector); + break; + + // TODO will the following handle all cases properly, or are elses going to be needed? + case mkTag('s', 'u', 'p', 's'): + if (value != 0) + f(kVerticalPositionType, kSuperiorsSelector); + break; + case mkTag('s', 'u', 'b', 's'): + if (value != 0) + f(kVerticalPositionType, kInferiorsSelector); + break; + case mkTag('o', 'r', 'd', 'n'): + if (value != 0) + f(kVerticalPositionType, kOrdinalsSelector); + break; + case mkTag('s', 'i', 'n', 'f'): + if (value != 0) + f(kVerticalPositionType, kScientificInferiorsSelector); + break; + + // TODO will the following handle all cases properly, or are elses going to be needed? + case mkTag('a', 'f', 'r', 'c'): + if (value != 0) + f(kFractionsType, kVerticalFractionsSelector); + break; + case mkTag('f', 'r', 'a', 'c'): + if (value != 0) + f(kFractionsType, kDiagonalFractionsSelector); + break; + + case mkTag('z', 'e', 'r', 'o'): + boolspec(value, kTypographicExtrasType, + kSlashedZeroOnSelector, + kSlashedZeroOffSelector, + f); + break; + case mkTag('m', 'g', 'r', 'k'): + boolspec(value, kMathematicalExtrasType, + kMathematicalGreekOnSelector, + kMathematicalGreekOffSelector, + f); + break; + case mkTag('o', 'r', 'n', 'm'): + f(kOrnamentSetsType, (uint16_t) value); + break; + case mkTag('a', 'a', 'l', 't'): + f(kCharacterAlternativesType, (uint16_t) value); + break; + case mkTag('t', 'i', 't', 'l'): + // TODO is this correct, or should we provide an else case? + if (value != 0) + f(kStyleOptionsType, kTitlingCapsSelector); + break; + + // TODO will the following handle all cases properly, or are elses going to be needed? + case mkTag('t', 'r', 'a', 'd'): + if (value != 0) + f(kCharacterShapeType, kTraditionalCharactersSelector); + break; + case mkTag('s', 'm', 'p', 'l'): + if (value != 0) + f(kCharacterShapeType, kSimplifiedCharactersSelector); + break; + case mkTag('j', 'p', '7', '8'): + if (value != 0) + f(kCharacterShapeType, kJIS1978CharactersSelector); + break; + case mkTag('j', 'p', '8', '3'): + if (value != 0) + f(kCharacterShapeType, kJIS1983CharactersSelector); + break; + case mkTag('j', 'p', '9', '0'): + if (value != 0) + f(kCharacterShapeType, kJIS1990CharactersSelector); + break; + case mkTag('e', 'x', 'p', 't'): + if (value != 0) + f(kCharacterShapeType, kExpertCharactersSelector); + break; + case mkTag('j', 'p', '0', '4'): + if (value != 0) + f(kCharacterShapeType, kJIS2004CharactersSelector); + break; + case mkTag('h', 'o', 'j', 'o'): + if (value != 0) + f(kCharacterShapeType, kHojoCharactersSelector); + break; + case mkTag('n', 'l', 'c', 'k'): + if (value != 0) + f(kCharacterShapeType, kNLCCharactersSelector); + break; + case mkTag('t', 'n', 'a', 'm'): + if (value != 0) + f(kCharacterShapeType, kTraditionalNamesCharactersSelector); + break; + + case mkTag('o', 'n', 'u', 'm'): + // Core Text's internal AAT-to-OpenType mapping says to include this, so we include it too + // TODO is it always set? + case mkTag('l', 'n', 'u', 'm'): + // TODO is this correct, or should we provide an else case? + if (value != 0) + f(kNumberCaseType, kLowerCaseNumbersSelector); + break; + case mkTag('h', 'n', 'g', 'l'): + // TODO is this correct, or should we provide an else case? + if (value != 0) + f(kTransliterationType, kHanjaToHangulSelector); + break; + case mkTag('n', 'a', 'l', 't'): + f(kAnnotationType, (uint16_t) value); + break; + case mkTag('r', 'u', 'b', 'y'): + // include this for completeness + boolspec(value, kRubyKanaType, + kRubyKanaSelector, + kNoRubyKanaSelector, + f); + // this is the current one + boolspec(value, kRubyKanaType, + kRubyKanaOnSelector, + kRubyKanaOffSelector, + f); + break; + case mkTag('i', 't', 'a', 'l'): + // include this for completeness + boolspec(value, kItalicCJKRomanType, + kCJKItalicRomanSelector, + kNoCJKItalicRomanSelector, + f); + // this is the current one + boolspec(value, kItalicCJKRomanType, + kCJKItalicRomanOnSelector, + kCJKItalicRomanOffSelector, + f); + break; + case mkTag('c', 'a', 's', 'e'): + boolspec(value, kCaseSensitiveLayoutType, + kCaseSensitiveLayoutOnSelector, + kCaseSensitiveLayoutOffSelector, + f); + break; + case mkTag('c', 'p', 's', 'p'): + boolspec(value, kCaseSensitiveLayoutType, + kCaseSensitiveSpacingOnSelector, + kCaseSensitiveSpacingOffSelector, + f); + break; + case mkTag('h', 'k', 'n', 'a'): + boolspec(value, kAlternateKanaType, + kAlternateHorizKanaOnSelector, + kAlternateHorizKanaOffSelector, + f); + break; + case mkTag('v', 'k', 'n', 'a'): + boolspec(value, kAlternateKanaType, + kAlternateVertKanaOnSelector, + kAlternateVertKanaOffSelector, + f); + break; + case mkTag('s', 's', '0', '1'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltOneOnSelector, + kStylisticAltOneOffSelector, + f); + break; + case mkTag('s', 's', '0', '2'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltTwoOnSelector, + kStylisticAltTwoOffSelector, + f); + break; + case mkTag('s', 's', '0', '3'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltThreeOnSelector, + kStylisticAltThreeOffSelector, + f); + break; + case mkTag('s', 's', '0', '4'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltFourOnSelector, + kStylisticAltFourOffSelector, + f); + break; + case mkTag('s', 's', '0', '5'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltFiveOnSelector, + kStylisticAltFiveOffSelector, + f); + break; + case mkTag('s', 's', '0', '6'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltSixOnSelector, + kStylisticAltSixOffSelector, + f); + break; + case mkTag('s', 's', '0', '7'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltSevenOnSelector, + kStylisticAltSevenOffSelector, + f); + break; + case mkTag('s', 's', '0', '8'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltEightOnSelector, + kStylisticAltEightOffSelector, + f); + break; + case mkTag('s', 's', '0', '9'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltNineOnSelector, + kStylisticAltNineOffSelector, + f); + break; + case mkTag('s', 's', '1', '0'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltTenOnSelector, + kStylisticAltTenOffSelector, + f); + break; + case mkTag('s', 's', '1', '1'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltElevenOnSelector, + kStylisticAltElevenOffSelector, + f); + break; + case mkTag('s', 's', '1', '2'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltTwelveOnSelector, + kStylisticAltTwelveOffSelector, + f); + break; + case mkTag('s', 's', '1', '3'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltThirteenOnSelector, + kStylisticAltThirteenOffSelector, + f); + break; + case mkTag('s', 's', '1', '4'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltFourteenOnSelector, + kStylisticAltFourteenOffSelector, + f); + break; + case mkTag('s', 's', '1', '5'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltFifteenOnSelector, + kStylisticAltFifteenOffSelector, + f); + break; + case mkTag('s', 's', '1', '6'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltSixteenOnSelector, + kStylisticAltSixteenOffSelector, + f); + break; + case mkTag('s', 's', '1', '7'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltSeventeenOnSelector, + kStylisticAltSeventeenOffSelector, + f); + break; + case mkTag('s', 's', '1', '8'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltEighteenOnSelector, + kStylisticAltEighteenOffSelector, + f); + break; + case mkTag('s', 's', '1', '9'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltNineteenOnSelector, + kStylisticAltNineteenOffSelector, + f); + break; + case mkTag('s', 's', '2', '0'): + boolspec(value, kStylisticAlternativesType, + kStylisticAltTwentyOnSelector, + kStylisticAltTwentyOffSelector, + f); + break; + case mkTag('c', 'a', 'l', 't'): + boolspec(value, kContextualAlternatesType, + kContextualAlternatesOnSelector, + kContextualAlternatesOffSelector, + f); + break; + case mkTag('s', 'w', 's', 'h'): + boolspec(value, kContextualAlternatesType, + kSwashAlternatesOnSelector, + kSwashAlternatesOffSelector, + f); + break; + case mkTag('c', 's', 'w', 'h'): + boolspec(value, kContextualAlternatesType, + kContextualSwashAlternatesOnSelector, + kContextualSwashAlternatesOffSelector, + f); + break; + + // TODO will the following handle all cases properly, or are elses going to be needed? + case mkTag('s', 'm', 'c', 'p'): + if (value != 0) { + // include this for compatibility (some fonts that come with OS X still use this!) + // TODO make it boolean? + f(kLetterCaseType, kSmallCapsSelector); + // this is the current one + f(kLowerCaseType, kLowerCaseSmallCapsSelector); + } + break; + case mkTag('p', 'c', 'a', 'p'): + if (value != 0) + f(kLowerCaseType, kLowerCasePetiteCapsSelector); + break; + + // TODO will the following handle all cases properly, or are elses going to be needed? + case mkTag('c', '2', 's', 'c'): + if (value != 0) + f(kUpperCaseType, kUpperCaseSmallCapsSelector); + break; + case mkTag('c', '2', 'p', 'c'): + if (value != 0) + f(kUpperCaseType, kUpperCasePetiteCapsSelector); + break; + } + // TODO handle this properly + // (it used to return 0 when this still returned the number of selectors produced but IDK what properly is anymore) +} diff --git a/dep/libui/darwin/alloc.m b/dep/libui/darwin/alloc.m new file mode 100644 index 0000000..e20f67f --- /dev/null +++ b/dep/libui/darwin/alloc.m @@ -0,0 +1,89 @@ +// 4 december 2014 +#import +#import "uipriv_darwin.h" + +static NSMutableArray *allocations; +NSMutableArray *uiprivDelegates; + +void uiprivInitAlloc(void) +{ + allocations = [NSMutableArray new]; + uiprivDelegates = [NSMutableArray new]; +} + +#define UINT8(p) ((uint8_t *) (p)) +#define PVOID(p) ((void *) (p)) +#define EXTRA (sizeof (size_t) + sizeof (const char **)) +#define DATA(p) PVOID(UINT8(p) + EXTRA) +#define BASE(p) PVOID(UINT8(p) - EXTRA) +#define SIZE(p) ((size_t *) (p)) +#define CCHAR(p) ((const char **) (p)) +#define TYPE(p) CCHAR(UINT8(p) + sizeof (size_t)) + +void uiprivUninitAlloc(void) +{ + NSMutableString *str; + NSValue *v; + + [uiprivDelegates release]; + if ([allocations count] == 0) { + [allocations release]; + return; + } + str = [NSMutableString new]; + for (v in allocations) { + void *ptr; + + ptr = [v pointerValue]; + [str appendString:[NSString stringWithFormat:@"%p %s\n", ptr, *TYPE(ptr)]]; + } + uiprivUserBug("Some data was leaked; either you left a uiControl lying around or there's a bug in libui itself. Leaked data:\n%s", [str UTF8String]); + [str release]; +} + +void *uiprivAlloc(size_t size, const char *type) +{ + void *out; + + out = malloc(EXTRA + size); + if (out == NULL) { + fprintf(stderr, "memory exhausted in uiAlloc()\n"); + abort(); + } + memset(DATA(out), 0, size); + *SIZE(out) = size; + *TYPE(out) = type; + [allocations addObject:[NSValue valueWithPointer:out]]; + return DATA(out); +} + +void *uiprivRealloc(void *p, size_t new, const char *type) +{ + void *out; + size_t *s; + + if (p == NULL) + return uiprivAlloc(new, type); + p = BASE(p); + out = realloc(p, EXTRA + new); + if (out == NULL) { + fprintf(stderr, "memory exhausted in uiprivRealloc()\n"); + abort(); + } + s = SIZE(out); + if (new > *s) + memset(((uint8_t *) DATA(out)) + *s, 0, new - *s); + *s = new; + [allocations removeObject:[NSValue valueWithPointer:p]]; + [allocations addObject:[NSValue valueWithPointer:out]]; + return DATA(out); +} + +void uiprivFree(void *p) +{ + if (p == NULL) + uiprivImplBug("attempt to uiprivFree(NULL)"); + p = BASE(p); + free(p); + [allocations removeObject:[NSValue valueWithPointer:p]]; +} diff --git a/dep/libui/darwin/area.m b/dep/libui/darwin/area.m new file mode 100644 index 0000000..a184bc4 --- /dev/null +++ b/dep/libui/darwin/area.m @@ -0,0 +1,474 @@ +// 9 september 2015 +#import "uipriv_darwin.h" + +// 10.8 fixups +#define NSEventModifierFlags NSUInteger + +@interface areaView : NSView { + uiArea *libui_a; + NSTrackingArea *libui_ta; + NSSize libui_ss; + BOOL libui_enabled; +} +- (id)initWithFrame:(NSRect)r area:(uiArea *)a; +- (uiModifiers)parseModifiers:(NSEvent *)e; +- (void)doMouseEvent:(NSEvent *)e; +- (int)sendKeyEvent:(uiAreaKeyEvent *)ke; +- (int)doKeyDownUp:(NSEvent *)e up:(int)up; +- (int)doKeyDown:(NSEvent *)e; +- (int)doKeyUp:(NSEvent *)e; +- (int)doFlagsChanged:(NSEvent *)e; +- (void)setupNewTrackingArea; +- (void)setScrollingSize:(NSSize)s; +- (BOOL)isEnabled; +- (void)setEnabled:(BOOL)e; +@end + +struct uiArea { + uiDarwinControl c; + NSView *view; // either sv or area depending on whether it is scrolling + NSScrollView *sv; + areaView *area; + uiprivScrollViewData *d; + uiAreaHandler *ah; + BOOL scrolling; + NSEvent *dragevent; +}; + +@implementation areaView + +- (id)initWithFrame:(NSRect)r area:(uiArea *)a +{ + self = [super initWithFrame:r]; + if (self) { + self->libui_a = a; + [self setupNewTrackingArea]; + self->libui_ss = r.size; + self->libui_enabled = YES; + } + return self; +} + +- (void)drawRect:(NSRect)r +{ + uiArea *a = self->libui_a; + CGContextRef c; + uiAreaDrawParams dp; + + c = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort]; + // see draw.m under text for why we need the height + dp.Context = uiprivDrawNewContext(c, [self bounds].size.height); + + dp.AreaWidth = 0; + dp.AreaHeight = 0; + if (!a->scrolling) { + dp.AreaWidth = [self frame].size.width; + dp.AreaHeight = [self frame].size.height; + } + + dp.ClipX = r.origin.x; + dp.ClipY = r.origin.y; + dp.ClipWidth = r.size.width; + dp.ClipHeight = r.size.height; + + // no need to save or restore the graphics state to reset transformations; Cocoa creates a brand-new context each time + (*(a->ah->Draw))(a->ah, a, &dp); + + uiprivDrawFreeContext(dp.Context); +} + +- (BOOL)isFlipped +{ + return YES; +} + +- (BOOL)acceptsFirstResponder +{ + return YES; +} + +- (uiModifiers)parseModifiers:(NSEvent *)e +{ + NSEventModifierFlags mods; + uiModifiers m; + + m = 0; + mods = [e modifierFlags]; + if ((mods & NSControlKeyMask) != 0) + m |= uiModifierCtrl; + if ((mods & NSAlternateKeyMask) != 0) + m |= uiModifierAlt; + if ((mods & NSShiftKeyMask) != 0) + m |= uiModifierShift; + if ((mods & NSCommandKeyMask) != 0) + m |= uiModifierSuper; + return m; +} + +- (void)setupNewTrackingArea +{ + self->libui_ta = [[NSTrackingArea alloc] initWithRect:[self bounds] + options:(NSTrackingMouseEnteredAndExited | + NSTrackingMouseMoved | + NSTrackingActiveAlways | + NSTrackingInVisibleRect | + NSTrackingEnabledDuringMouseDrag) + owner:self + userInfo:nil]; + [self addTrackingArea:self->libui_ta]; +} + +- (void)updateTrackingAreas +{ + [self removeTrackingArea:self->libui_ta]; + [self->libui_ta release]; + [self setupNewTrackingArea]; +} + +// capture on drag is done automatically on OS X +- (void)doMouseEvent:(NSEvent *)e +{ + uiArea *a = self->libui_a; + uiAreaMouseEvent me; + NSPoint point; + int buttonNumber; + NSUInteger pmb; + unsigned int i, max; + + // this will convert point to drawing space + // thanks swillits in irc.freenode.net/#macdev + point = [self convertPoint:[e locationInWindow] fromView:nil]; + me.X = point.x; + me.Y = point.y; + + me.AreaWidth = 0; + me.AreaHeight = 0; + if (!a->scrolling) { + me.AreaWidth = [self frame].size.width; + me.AreaHeight = [self frame].size.height; + } + + buttonNumber = [e buttonNumber] + 1; + // swap button numbers 2 and 3 (right and middle) + if (buttonNumber == 2) + buttonNumber = 3; + else if (buttonNumber == 3) + buttonNumber = 2; + + me.Down = 0; + me.Up = 0; + me.Count = 0; + switch ([e type]) { + case NSLeftMouseDown: + case NSRightMouseDown: + case NSOtherMouseDown: + me.Down = buttonNumber; + me.Count = [e clickCount]; + break; + case NSLeftMouseUp: + case NSRightMouseUp: + case NSOtherMouseUp: + me.Up = buttonNumber; + break; + case NSLeftMouseDragged: + case NSRightMouseDragged: + case NSOtherMouseDragged: + // we include the button that triggered the dragged event in the Held fields + buttonNumber = 0; + break; + } + + me.Modifiers = [self parseModifiers:e]; + + pmb = [NSEvent pressedMouseButtons]; + me.Held1To64 = 0; + if (buttonNumber != 1 && (pmb & 1) != 0) + me.Held1To64 |= 1; + if (buttonNumber != 2 && (pmb & 4) != 0) + me.Held1To64 |= 2; + if (buttonNumber != 3 && (pmb & 2) != 0) + me.Held1To64 |= 4; + // buttons 4..32 + // https://developer.apple.com/library/mac/documentation/Carbon/Reference/QuartzEventServicesRef/index.html#//apple_ref/c/tdef/CGMouseButton says Quartz only supports up to 32 buttons + max = 32; + for (i = 4; i <= max; i++) { + uint64_t j; + + if (buttonNumber == i) + continue; + j = 1 << (i - 1); + if ((pmb & j) != 0) + me.Held1To64 |= j; + } + + if (self->libui_enabled) { + // and allow dragging here + a->dragevent = e; + (*(a->ah->MouseEvent))(a->ah, a, &me); + a->dragevent = nil; + } +} + +#define mouseEvent(name) \ + - (void)name:(NSEvent *)e \ + { \ + [self doMouseEvent:e]; \ + } +mouseEvent(mouseMoved) +mouseEvent(mouseDragged) +mouseEvent(rightMouseDragged) +mouseEvent(otherMouseDragged) +mouseEvent(mouseDown) +mouseEvent(rightMouseDown) +mouseEvent(otherMouseDown) +mouseEvent(mouseUp) +mouseEvent(rightMouseUp) +mouseEvent(otherMouseUp) + +- (void)mouseEntered:(NSEvent *)e +{ + uiArea *a = self->libui_a; + + if (self->libui_enabled) + (*(a->ah->MouseCrossed))(a->ah, a, 0); +} + +- (void)mouseExited:(NSEvent *)e +{ + uiArea *a = self->libui_a; + + if (self->libui_enabled) + (*(a->ah->MouseCrossed))(a->ah, a, 1); +} + +// note: there is no equivalent to WM_CAPTURECHANGED on Mac OS X; there literally is no way to break a grab like that +// even if I invoke the task switcher and switch processes, the mouse grab will still be held until I let go of all buttons +// therefore, no DragBroken() + +- (int)sendKeyEvent:(uiAreaKeyEvent *)ke +{ + uiArea *a = self->libui_a; + + return (*(a->ah->KeyEvent))(a->ah, a, ke); +} + +- (int)doKeyDownUp:(NSEvent *)e up:(int)up +{ + uiAreaKeyEvent ke; + + ke.Key = 0; + ke.ExtKey = 0; + ke.Modifier = 0; + + ke.Modifiers = [self parseModifiers:e]; + + ke.Up = up; + + if (!uiprivFromKeycode([e keyCode], &ke)) + return 0; + return [self sendKeyEvent:&ke]; +} + +- (int)doKeyDown:(NSEvent *)e +{ + return [self doKeyDownUp:e up:0]; +} + +- (int)doKeyUp:(NSEvent *)e +{ + return [self doKeyDownUp:e up:1]; +} + +- (int)doFlagsChanged:(NSEvent *)e +{ + uiAreaKeyEvent ke; + uiModifiers whichmod; + + ke.Key = 0; + ke.ExtKey = 0; + + // Mac OS X sends this event on both key up and key down. + // Fortunately -[e keyCode] IS valid here, so we can simply map from key code to Modifiers, get the value of [e modifierFlags], and check if the respective bit is set or not — that will give us the up/down state + if (!uiprivKeycodeModifier([e keyCode], &whichmod)) + return 0; + ke.Modifier = whichmod; + ke.Modifiers = [self parseModifiers:e]; + ke.Up = (ke.Modifiers & ke.Modifier) == 0; + // and then drop the current modifier from Modifiers + ke.Modifiers &= ~ke.Modifier; + return [self sendKeyEvent:&ke]; +} + +- (void)setFrameSize:(NSSize)size +{ + uiArea *a = self->libui_a; + + [super setFrameSize:size]; + if (!a->scrolling) + // we must redraw everything on resize because Windows requires it + [self setNeedsDisplay:YES]; +} + +- (void)setScrollingSize:(NSSize)s +{ + self->libui_ss = s; + [self setFrameSize:s]; +} + +- (NSSize)intrinsicContentSize +{ + if (!self->libui_a->scrolling) + return [super intrinsicContentSize]; + return self->libui_ss; +} + +- (BOOL)becomeFirstResponder +{ + return [self isEnabled]; +} + +- (BOOL)isEnabled +{ + return self->libui_enabled; +} + +- (void)setEnabled:(BOOL)e +{ + self->libui_enabled = e; + if (!self->libui_enabled && [self window] != nil) + if ([[self window] firstResponder] == self) + [[self window] makeFirstResponder:nil]; +} + +@end + +uiDarwinControlAllDefaultsExceptDestroy(uiArea, view) + +static void uiAreaDestroy(uiControl *c) +{ + uiArea *a = uiArea(c); + + if (a->scrolling) + uiprivScrollViewFreeData(a->sv, a->d); + [a->area release]; + if (a->scrolling) + [a->sv release]; + uiFreeControl(uiControl(a)); +} + +// called by subclasses of -[NSApplication sendEvent:] +// by default, NSApplication eats some key events +// this prevents that from happening with uiArea +// see http://stackoverflow.com/questions/24099063/how-do-i-detect-keyup-in-my-nsview-with-the-command-key-held and http://lists.apple.com/archives/cocoa-dev/2003/Oct/msg00442.html +int uiprivSendAreaEvents(NSEvent *e) +{ + NSEventType type; + id focused; + areaView *view; + + type = [e type]; + if (type != NSKeyDown && type != NSKeyUp && type != NSFlagsChanged) + return 0; + focused = [[e window] firstResponder]; + if (focused == nil) + return 0; + if (![focused isKindOfClass:[areaView class]]) + return 0; + view = (areaView *) focused; + switch (type) { + case NSKeyDown: + return [view doKeyDown:e]; + case NSKeyUp: + return [view doKeyUp:e]; + case NSFlagsChanged: + return [view doFlagsChanged:e]; + } + return 0; +} + +void uiAreaSetSize(uiArea *a, int width, int height) +{ + if (!a->scrolling) + uiprivUserBug("You cannot call uiAreaSetSize() on a non-scrolling uiArea. (area: %p)", a); + [a->area setScrollingSize:NSMakeSize(width, height)]; +} + +void uiAreaQueueRedrawAll(uiArea *a) +{ + [a->area setNeedsDisplay:YES]; +} + +void uiAreaScrollTo(uiArea *a, double x, double y, double width, double height) +{ + if (!a->scrolling) + uiprivUserBug("You cannot call uiAreaScrollTo() on a non-scrolling uiArea. (area: %p)", a); + [a->area scrollRectToVisible:NSMakeRect(x, y, width, height)]; + // don't worry about the return value; it just says whether scrolling was needed +} + +void uiAreaBeginUserWindowMove(uiArea *a) +{ + uiprivNSWindow *w; + + w = (uiprivNSWindow *) [a->area window]; + if (w == nil) + return; // TODO + if (a->dragevent == nil) + return; // TODO + [w uiprivDoMove:a->dragevent]; +} + +void uiAreaBeginUserWindowResize(uiArea *a, uiWindowResizeEdge edge) +{ + uiprivNSWindow *w; + + w = (uiprivNSWindow *) [a->area window]; + if (w == nil) + return; // TODO + if (a->dragevent == nil) + return; // TODO + [w uiprivDoResize:a->dragevent on:edge]; +} + +uiArea *uiNewArea(uiAreaHandler *ah) +{ + uiArea *a; + + uiDarwinNewControl(uiArea, a); + + a->ah = ah; + a->scrolling = NO; + + a->area = [[areaView alloc] initWithFrame:NSZeroRect area:a]; + + a->view = a->area; + + return a; +} + +uiArea *uiNewScrollingArea(uiAreaHandler *ah, int width, int height) +{ + uiArea *a; + uiprivScrollViewCreateParams p; + + uiDarwinNewControl(uiArea, a); + + a->ah = ah; + a->scrolling = YES; + + a->area = [[areaView alloc] initWithFrame:NSMakeRect(0, 0, width, height) + area:a]; + + memset(&p, 0, sizeof (uiprivScrollViewCreateParams)); + p.DocumentView = a->area; + p.BackgroundColor = [NSColor controlColor]; + p.DrawsBackground = 1; + p.Bordered = NO; + p.HScroll = YES; + p.VScroll = YES; + a->sv = uiprivMkScrollView(&p, &(a->d)); + + a->view = a->sv; + + return a; +} diff --git a/dep/libui/darwin/areaevents.m b/dep/libui/darwin/areaevents.m new file mode 100644 index 0000000..27b5dd6 --- /dev/null +++ b/dep/libui/darwin/areaevents.m @@ -0,0 +1,159 @@ +// 30 march 2014 +#import "uipriv_darwin.h" + +/* +Mac OS X uses its own set of hardware key codes that are different from PC keyboard scancodes, but are positional (like PC keyboard scancodes). These are defined in , a Carbon header. As far as I can tell, there's no way to include this header without either using an absolute path or linking Carbon into the program, so the constant values are used here instead. + +The Cocoa docs do guarantee that -[NSEvent keyCode] results in key codes that are the same as those returned by Carbon; that is, these codes. +*/ + +// use uintptr_t to be safe +static const struct { + uintptr_t keycode; + char equiv; +} keycodeKeys[] = { + { 0x00, 'a' }, + { 0x01, 's' }, + { 0x02, 'd' }, + { 0x03, 'f' }, + { 0x04, 'h' }, + { 0x05, 'g' }, + { 0x06, 'z' }, + { 0x07, 'x' }, + { 0x08, 'c' }, + { 0x09, 'v' }, + { 0x0B, 'b' }, + { 0x0C, 'q' }, + { 0x0D, 'w' }, + { 0x0E, 'e' }, + { 0x0F, 'r' }, + { 0x10, 'y' }, + { 0x11, 't' }, + { 0x12, '1' }, + { 0x13, '2' }, + { 0x14, '3' }, + { 0x15, '4' }, + { 0x16, '6' }, + { 0x17, '5' }, + { 0x18, '=' }, + { 0x19, '9' }, + { 0x1A, '7' }, + { 0x1B, '-' }, + { 0x1C, '8' }, + { 0x1D, '0' }, + { 0x1E, ']' }, + { 0x1F, 'o' }, + { 0x20, 'u' }, + { 0x21, '[' }, + { 0x22, 'i' }, + { 0x23, 'p' }, + { 0x25, 'l' }, + { 0x26, 'j' }, + { 0x27, '\'' }, + { 0x28, 'k' }, + { 0x29, ';' }, + { 0x2A, '\\' }, + { 0x2B, ',' }, + { 0x2C, '/' }, + { 0x2D, 'n' }, + { 0x2E, 'm' }, + { 0x2F, '.' }, + { 0x32, '`' }, + { 0x24, '\n' }, + { 0x30, '\t' }, + { 0x31, ' ' }, + { 0x33, '\b' }, + { 0xFFFF, 0 }, +}; + +static const struct { + uintptr_t keycode; + uiExtKey equiv; +} keycodeExtKeys[] = { + { 0x41, uiExtKeyNDot }, + { 0x43, uiExtKeyNMultiply }, + { 0x45, uiExtKeyNAdd }, + { 0x4B, uiExtKeyNDivide }, + { 0x4C, uiExtKeyNEnter }, + { 0x4E, uiExtKeyNSubtract }, + { 0x52, uiExtKeyN0 }, + { 0x53, uiExtKeyN1 }, + { 0x54, uiExtKeyN2 }, + { 0x55, uiExtKeyN3 }, + { 0x56, uiExtKeyN4 }, + { 0x57, uiExtKeyN5 }, + { 0x58, uiExtKeyN6 }, + { 0x59, uiExtKeyN7 }, + { 0x5B, uiExtKeyN8 }, + { 0x5C, uiExtKeyN9 }, + { 0x35, uiExtKeyEscape }, + { 0x60, uiExtKeyF5 }, + { 0x61, uiExtKeyF6 }, + { 0x62, uiExtKeyF7 }, + { 0x63, uiExtKeyF3 }, + { 0x64, uiExtKeyF8 }, + { 0x65, uiExtKeyF9 }, + { 0x67, uiExtKeyF11 }, + { 0x6D, uiExtKeyF10 }, + { 0x6F, uiExtKeyF12 }, + { 0x72, uiExtKeyInsert }, // listed as the Help key but it's in the same position on an Apple keyboard as the Insert key on a Windows keyboard; thanks to SeanieB from irc.badnik.net and Psy in irc.freenode.net/#macdev for confirming they have the same code + { 0x73, uiExtKeyHome }, + { 0x74, uiExtKeyPageUp }, + { 0x75, uiExtKeyDelete }, + { 0x76, uiExtKeyF4 }, + { 0x77, uiExtKeyEnd }, + { 0x78, uiExtKeyF2 }, + { 0x79, uiExtKeyPageDown }, + { 0x7A, uiExtKeyF1 }, + { 0x7B, uiExtKeyLeft }, + { 0x7C, uiExtKeyRight }, + { 0x7D, uiExtKeyDown }, + { 0x7E, uiExtKeyUp }, + { 0xFFFF, 0 }, +}; + +static const struct { + uintptr_t keycode; + uiModifiers equiv; +} keycodeModifiers[] = { + { 0x37, uiModifierSuper }, // left command + { 0x38, uiModifierShift }, // left shift + { 0x3A, uiModifierAlt }, // left option + { 0x3B, uiModifierCtrl }, // left control + { 0x3C, uiModifierShift }, // right shift + { 0x3D, uiModifierAlt }, // right alt + { 0x3E, uiModifierCtrl }, // right control + // the following is not in Events.h for some reason + // thanks to Nicole and jedivulcan from irc.badnik.net + { 0x36, uiModifierSuper }, // right command + { 0xFFFF, 0 }, +}; + +BOOL uiprivFromKeycode(unsigned short keycode, uiAreaKeyEvent *ke) +{ + int i; + + for (i = 0; keycodeKeys[i].keycode != 0xFFFF; i++) + if (keycodeKeys[i].keycode == keycode) { + ke->Key = keycodeKeys[i].equiv; + return YES; + } + for (i = 0; keycodeExtKeys[i].keycode != 0xFFFF; i++) + if (keycodeExtKeys[i].keycode == keycode) { + ke->ExtKey = keycodeExtKeys[i].equiv; + return YES; + } + return NO; +} + +BOOL uiprivKeycodeModifier(unsigned short keycode, uiModifiers *mod) +{ + int i; + + for (i = 0; keycodeModifiers[i].keycode != 0xFFFF; i++) + if (keycodeModifiers[i].keycode == keycode) { + *mod = keycodeModifiers[i].equiv; + return YES; + } + return NO; +} diff --git a/dep/libui/darwin/attrstr.h b/dep/libui/darwin/attrstr.h new file mode 100644 index 0000000..02a3418 --- /dev/null +++ b/dep/libui/darwin/attrstr.h @@ -0,0 +1,91 @@ +// 4 march 2018 +#import "../common/attrstr.h" + +// opentype.m +extern CFArrayRef uiprivOpenTypeFeaturesToCTFeatures(const uiOpenTypeFeatures *otf); + +// aat.m +typedef void (^uiprivAATBlock)(uint16_t type, uint16_t selector); +extern void uiprivOpenTypeToAAT(char a, char b, char c, char d, uint32_t value, uiprivAATBlock f); + +// fontmatch.m +@interface uiprivFontStyleData : NSObject { + CTFontRef font; + CTFontDescriptorRef desc; + CFDictionaryRef traits; + CTFontSymbolicTraits symbolic; + double weight; + double width; + BOOL didStyleName; + CFStringRef styleName; + BOOL didVariation; + CFDictionaryRef variation; + BOOL hasRegistrationScope; + CTFontManagerScope registrationScope; + BOOL didPostScriptName; + CFStringRef postScriptName; + CTFontFormat fontFormat; + BOOL didPreferredSubFamilyName; + CFStringRef preferredSubFamilyName; + BOOL didSubFamilyName; + CFStringRef subFamilyName; + BOOL didFullName; + CFStringRef fullName; + BOOL didPreferredFamilyName; + CFStringRef preferredFamilyName; + BOOL didFamilyName; + CFStringRef familyName; + BOOL didVariationAxes; + CFArrayRef variationAxes; +} +- (id)initWithFont:(CTFontRef)f; +- (id)initWithDescriptor:(CTFontDescriptorRef)d; +- (BOOL)prepare; +- (void)ensureFont; +- (CTFontSymbolicTraits)symbolicTraits; +- (double)weight; +- (double)width; +- (CFStringRef)styleName; +- (CFDictionaryRef)variation; +- (BOOL)hasRegistrationScope; +- (CTFontManagerScope)registrationScope; +- (CFStringRef)postScriptName; +- (CFDataRef)table:(CTFontTableTag)tag; +- (CTFontFormat)fontFormat; +- (CFStringRef)fontName:(CFStringRef)key; +- (CFStringRef)preferredSubFamilyName; +- (CFStringRef)subFamilyName; +- (CFStringRef)fullName; +- (CFStringRef)preferredFamilyName; +- (CFStringRef)familyName; +- (CFArrayRef)variationAxes; +@end +extern CTFontDescriptorRef uiprivFontDescriptorToCTFontDescriptor(uiFontDescriptor *fd); +extern CTFontDescriptorRef uiprivCTFontDescriptorAppendFeatures(CTFontDescriptorRef desc, const uiOpenTypeFeatures *otf); +extern void uiprivFontDescriptorFromCTFontDescriptor(CTFontDescriptorRef ctdesc, uiFontDescriptor *uidesc); + +// fonttraits.m +extern void uiprivProcessFontTraits(uiprivFontStyleData *d, uiFontDescriptor *out); + +// fontvariation.m +extern NSDictionary *uiprivMakeVariationAxisDict(CFArrayRef axes, CFDataRef avarTable); +extern void uiprivProcessFontVariation(uiprivFontStyleData *d, NSDictionary *axisDict, uiFontDescriptor *out); + +// attrstr.m +extern void uiprivInitUnderlineColors(void); +extern void uiprivUninitUnderlineColors(void); +extern CFAttributedStringRef uiprivAttributedStringToCFAttributedString(uiDrawTextLayoutParams *p, NSArray **backgroundParams); + +// drawtext.m +// TODO figure out where this type should *really* go in all the headers... +@interface uiprivDrawTextBackgroundParams : NSObject { + size_t start; + size_t end; + double r; + double g; + double b; + double a; +} +- (id)initWithStart:(size_t)s end:(size_t)e r:(double)red g:(double)green b:(double)blue a:(double)alpha; +- (void)draw:(CGContextRef)c layout:(uiDrawTextLayout *)layout at:(double)x y:(double)y utf8Mapping:(const size_t *)u16tou8; +@end diff --git a/dep/libui/darwin/attrstr.m b/dep/libui/darwin/attrstr.m new file mode 100644 index 0000000..36a180b --- /dev/null +++ b/dep/libui/darwin/attrstr.m @@ -0,0 +1,505 @@ +// 12 february 2017 +#import "uipriv_darwin.h" +#import "attrstr.h" + +// this is what AppKit does internally +// WebKit does this too; see https://github.com/adobe/webkit/blob/master/Source/WebCore/platform/graphics/mac/GraphicsContextMac.mm +static NSColor *spellingColor = nil; +static NSColor *grammarColor = nil; +static NSColor *auxiliaryColor = nil; + +static NSColor *tryColorNamed(NSString *name) +{ + NSImage *img; + + img = [NSImage imageNamed:name]; + if (img == nil) + return nil; + return [NSColor colorWithPatternImage:img]; +} + +void uiprivInitUnderlineColors(void) +{ + spellingColor = tryColorNamed(@"NSSpellingDot"); + if (spellingColor == nil) { + // WebKit says this is needed for "older systems"; not sure how old, but 10.11 AppKit doesn't look for this + spellingColor = tryColorNamed(@"SpellingDot"); + if (spellingColor == nil) + spellingColor = [NSColor redColor]; + } + [spellingColor retain]; // override autoreleasing + + grammarColor = tryColorNamed(@"NSGrammarDot"); + if (grammarColor == nil) { + // WebKit says this is needed for "older systems"; not sure how old, but 10.11 AppKit doesn't look for this + grammarColor = tryColorNamed(@"GrammarDot"); + if (grammarColor == nil) + grammarColor = [NSColor greenColor]; + } + [grammarColor retain]; // override autoreleasing + + auxiliaryColor = tryColorNamed(@"NSCorrectionDot"); + if (auxiliaryColor == nil) { + // WebKit says this is needed for "older systems"; not sure how old, but 10.11 AppKit doesn't look for this + auxiliaryColor = tryColorNamed(@"CorrectionDot"); + if (auxiliaryColor == nil) + auxiliaryColor = [NSColor blueColor]; + } + [auxiliaryColor retain]; // override autoreleasing +} + +void uiprivUninitUnderlineColors(void) +{ + [auxiliaryColor release]; + auxiliaryColor = nil; + [grammarColor release]; + grammarColor = nil; + [spellingColor release]; + spellingColor = nil; +} + +// TODO opentype features are lost when using uiFontDescriptor, so a handful of fonts in the font panel ("Titling" variants of some fonts and possibly others but those are the examples I know about) cannot be represented by uiFontDescriptor; what *can* we do about this since this info is NOT part of the font on other platforms? +// TODO see if we could use NSAttributedString? +// TODO consider renaming this struct and the fep variable(s) +// TODO restructure all this so the important details at the top are below with the combined font attributes type? +// TODO in fact I should just write something to explain everything in this file... +struct foreachParams { + CFMutableAttributedStringRef mas; + NSMutableArray *backgroundParams; +}; + +// unlike the other systems, Core Text rolls family, size, weight, italic, width, AND opentype features into the "font" attribute +// instead of incrementally adjusting CTFontRefs (which, judging from NSFontManager, seems finicky and UI-centric), we use a custom class to incrementally store attributes that go into a CTFontRef, and then convert everything to CTFonts en masse later +// https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/AttributedStrings/Tasks/ChangingAttrStrings.html#//apple_ref/doc/uid/20000162-BBCBGCDG says we must have -hash and -isEqual: workign properly for this to work, so we must do that too, using a basic xor-based hash and leveraging Cocoa -hash implementations where useful and feasible (if not necessary) +// TODO structure and rewrite this part +// TODO re-find sources proving support of custom attributes +// TODO what if this is NULL? +static const CFStringRef combinedFontAttrName = CFSTR("libuiCombinedFontAttribute"); + +enum { + cFamily, + cSize, + cWeight, + cItalic, + cStretch, + cFeatures, + nc, +}; + +static const int toc[] = { + [uiAttributeTypeFamily] = cFamily, + [uiAttributeTypeSize] = cSize, + [uiAttributeTypeWeight] = cWeight, + [uiAttributeTypeItalic] = cItalic, + [uiAttributeTypeStretch] = cStretch, + [uiAttributeTypeFeatures] = cFeatures, +}; + +static uiForEach featuresHash(const uiOpenTypeFeatures *otf, char a, char b, char c, char d, uint32_t value, void *data) +{ + NSUInteger *hash = (NSUInteger *) data; + uint32_t tag; + + tag = (((uint32_t) a) & 0xFF) << 24; + tag |= (((uint32_t) b) & 0xFF) << 16; + tag |= (((uint32_t) c) & 0xFF) << 8; + tag |= ((uint32_t) d) & 0xFF; + *hash ^= tag; + *hash ^= value; + return uiForEachContinue; +} + +@interface uiprivCombinedFontAttr : NSObject { + uiAttribute *attrs[nc]; + BOOL hasHash; + NSUInteger hash; +} +- (void)addAttribute:(uiAttribute *)attr; +- (CTFontRef)toCTFontWithDefaultFont:(uiFontDescriptor *)defaultFont; +@end + +@implementation uiprivCombinedFontAttr + +- (id)init +{ + self = [super init]; + if (self) { + memset(self->attrs, 0, nc * sizeof (uiAttribute *)); + self->hasHash = NO; + } + return self; +} + +- (void)dealloc +{ + int i; + + for (i = 0; i < nc; i++) + if (self->attrs[i] != NULL) { + uiprivAttributeRelease(self->attrs[i]); + self->attrs[i] = NULL; + } + [super dealloc]; +} + +- (id)copyWithZone:(NSZone *)zone +{ + uiprivCombinedFontAttr *ret; + int i; + + ret = [[uiprivCombinedFontAttr allocWithZone:zone] init]; + for (i = 0; i < nc; i++) + if (self->attrs[i] != NULL) + ret->attrs[i] = uiprivAttributeRetain(self->attrs[i]); + ret->hasHash = self->hasHash; + ret->hash = self->hash; + return ret; +} + +- (void)addAttribute:(uiAttribute *)attr +{ + int index; + + index = toc[uiAttributeGetType(attr)]; + if (self->attrs[index] != NULL) + uiprivAttributeRelease(self->attrs[index]); + self->attrs[index] = uiprivAttributeRetain(attr); + self->hasHash = NO; +} + +- (BOOL)isEqual:(id)bb +{ + uiprivCombinedFontAttr *b = (uiprivCombinedFontAttr *) bb; + int i; + + if (b == nil) + return NO; + for (i = 0; i < nc; i++) { + if (self->attrs[i] == NULL && b->attrs[i] == NULL) + continue; + if (self->attrs[i] == NULL || b->attrs[i] == NULL) + return NO; + if (!uiprivAttributeEqual(self->attrs[i], b->attrs[i])) + return NO; + } + return YES; +} + +- (NSUInteger)hash +{ + if (self->hasHash) + return self->hash; + @autoreleasepool { + NSString *family; + NSNumber *size; + + self->hash = 0; + if (self->attrs[cFamily] != NULL) { + family = [NSString stringWithUTF8String:uiAttributeFamily(self->attrs[cFamily])]; + // TODO make sure this aligns with case-insensitive compares when those are done in common/attribute.c + self->hash ^= [[family uppercaseString] hash]; + } + if (self->attrs[cSize] != NULL) { + size = [NSNumber numberWithDouble:uiAttributeSize(self->attrs[cSize])]; + self->hash ^= [size hash]; + } + if (self->attrs[cWeight] != NULL) + self->hash ^= (NSUInteger) uiAttributeWeight(self->attrs[cWeight]); + if (self->attrs[cItalic] != NULL) + self->hash ^= (NSUInteger) uiAttributeItalic(self->attrs[cItalic]); + if (self->attrs[cStretch] != NULL) + self->hash ^= (NSUInteger) uiAttributeStretch(self->attrs[cStretch]); + if (self->attrs[cFeatures] != NULL) + uiOpenTypeFeaturesForEach(uiAttributeFeatures(self->attrs[cFeatures]), featuresHash, &(self->hash)); + self->hasHash = YES; + } + return self->hash; +} + +- (CTFontRef)toCTFontWithDefaultFont:(uiFontDescriptor *)defaultFont +{ + uiFontDescriptor uidesc; + CTFontDescriptorRef desc; + CTFontRef font; + + uidesc = *defaultFont; + if (self->attrs[cFamily] != NULL) + // TODO const-correct uiFontDescriptor or change this function below + uidesc.Family = (char *) uiAttributeFamily(self->attrs[cFamily]); + if (self->attrs[cSize] != NULL) + uidesc.Size = uiAttributeSize(self->attrs[cSize]); + if (self->attrs[cWeight] != NULL) + uidesc.Weight = uiAttributeWeight(self->attrs[cWeight]); + if (self->attrs[cItalic] != NULL) + uidesc.Italic = uiAttributeItalic(self->attrs[cItalic]); + if (self->attrs[cStretch] != NULL) + uidesc.Stretch = uiAttributeStretch(self->attrs[cStretch]); + desc = uiprivFontDescriptorToCTFontDescriptor(&uidesc); + if (self->attrs[cFeatures] != NULL) + desc = uiprivCTFontDescriptorAppendFeatures(desc, uiAttributeFeatures(self->attrs[cFeatures])); + font = CTFontCreateWithFontDescriptor(desc, uidesc.Size, NULL); + CFRelease(desc); // TODO correct? + return font; +} + +@end + +static void addFontAttributeToRange(struct foreachParams *p, size_t start, size_t end, uiAttribute *attr) +{ + uiprivCombinedFontAttr *cfa; + CFRange range; + size_t diff; + + while (start < end) { + cfa = (uiprivCombinedFontAttr *) CFAttributedStringGetAttribute(p->mas, start, combinedFontAttrName, &range); + if (cfa == nil) + cfa = [uiprivCombinedFontAttr new]; + else + cfa = [cfa copy]; + [cfa addAttribute:attr]; + // clamp range within [start, end) + if (range.location < start) { + diff = start - range.location; + range.location = start; + range.length -= diff; + } + if ((range.location + range.length) > end) + range.length = end - range.location; + CFAttributedStringSetAttribute(p->mas, range, combinedFontAttrName, cfa); + [cfa release]; + start += range.length; + } +} + +static CGColorRef mkcolor(double r, double g, double b, double a) +{ + CGColorSpaceRef colorspace; + CGColorRef color; + CGFloat components[4]; + + // TODO we should probably just create this once and recycle it throughout program execution... + colorspace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB); + if (colorspace == NULL) { + // TODO + } + components[0] = r; + components[1] = g; + components[2] = b; + components[3] = a; + color = CGColorCreate(colorspace, components); + CFRelease(colorspace); + return color; +} + +static void addBackgroundAttribute(struct foreachParams *p, size_t start, size_t end, double r, double g, double b, double a) +{ + uiprivDrawTextBackgroundParams *dtb; + + // TODO make sure this works properly with line paragraph spacings (after figuring out what that means, of course) + if (uiprivFUTURE_kCTBackgroundColorAttributeName != NULL) { + CGColorRef color; + CFRange range; + + color = mkcolor(r, g, b, a); + range.location = start; + range.length = end - start; + CFAttributedStringSetAttribute(p->mas, range, *uiprivFUTURE_kCTBackgroundColorAttributeName, color); + CFRelease(color); + return; + } + + dtb = [[uiprivDrawTextBackgroundParams alloc] initWithStart:start end:end r:r g:g b:b a:a]; + [p->backgroundParams addObject:dtb]; + [dtb release]; +} + +static uiForEach processAttribute(const uiAttributedString *s, const uiAttribute *attr, size_t start, size_t end, void *data) +{ + struct foreachParams *p = (struct foreachParams *) data; + CFRange range; + CGColorRef color; + int32_t us; + CFNumberRef num; + double r, g, b, a; + uiUnderlineColor colorType; + + start = uiprivAttributedStringUTF8ToUTF16(s, start); + end = uiprivAttributedStringUTF8ToUTF16(s, end); + range.location = start; + range.length = end - start; + switch (uiAttributeGetType(attr)) { + case uiAttributeTypeFamily: + case uiAttributeTypeSize: + case uiAttributeTypeWeight: + case uiAttributeTypeItalic: + case uiAttributeTypeStretch: + case uiAttributeTypeFeatures: + addFontAttributeToRange(p, start, end, attr); + break; + case uiAttributeTypeColor: + uiAttributeColor(attr, &r, &g, &b, &a); + color = mkcolor(r, g, b, a); + CFAttributedStringSetAttribute(p->mas, range, kCTForegroundColorAttributeName, color); + CFRelease(color); + break; + case uiAttributeTypeBackground: + uiAttributeColor(attr, &r, &g, &b, &a); + addBackgroundAttribute(p, start, end, r, g, b, a); + break; + // TODO turn into a class, like we did with the font attributes, or even integrate *into* the font attributes + case uiAttributeTypeUnderline: + switch (uiAttributeUnderline(attr)) { + case uiUnderlineNone: + us = kCTUnderlineStyleNone; + break; + case uiUnderlineSingle: + us = kCTUnderlineStyleSingle; + break; + case uiUnderlineDouble: + us = kCTUnderlineStyleDouble; + break; + case uiUnderlineSuggestion: + // TODO incorrect if a solid color + us = kCTUnderlineStyleThick; + break; + } + num = CFNumberCreate(NULL, kCFNumberSInt32Type, &us); + CFAttributedStringSetAttribute(p->mas, range, kCTUnderlineStyleAttributeName, num); + CFRelease(num); + break; + case uiAttributeTypeUnderlineColor: + uiAttributeUnderlineColor(attr, &colorType, &r, &g, &b, &a); + switch (colorType) { + case uiUnderlineColorCustom: + color = mkcolor(r, g, b, a); + break; + case uiUnderlineColorSpelling: + color = [spellingColor CGColor]; + break; + case uiUnderlineColorGrammar: + color = [grammarColor CGColor]; + break; + case uiUnderlineColorAuxiliary: + color = [auxiliaryColor CGColor]; + break; + } + CFAttributedStringSetAttribute(p->mas, range, kCTUnderlineColorAttributeName, color); + if (colorType == uiUnderlineColorCustom) + CFRelease(color); + break; + } + return uiForEachContinue; +} + +static void applyFontAttributes(CFMutableAttributedStringRef mas, uiFontDescriptor *defaultFont) +{ + uiprivCombinedFontAttr *cfa; + CTFontRef font; + CFRange range; + CFIndex n; + + n = CFAttributedStringGetLength(mas); + + // first apply the default font to the entire string + // TODO is this necessary given the #if 0'd code in uiprivAttributedStringToCFAttributedString()? + cfa = [uiprivCombinedFontAttr new]; + font = [cfa toCTFontWithDefaultFont:defaultFont]; + [cfa release]; + range.location = 0; + range.length = n; + CFAttributedStringSetAttribute(mas, range, kCTFontAttributeName, font); + CFRelease(font); + + // now go through, replacing every uiprivCombinedFontAttr with the proper CTFontRef + // we are best off treating series of identical fonts as single ranges ourselves for parity across platforms, even if OS X does something similar itself + range.location = 0; + while (range.location < n) { + // TODO consider seeing if CFAttributedStringGetAttributeAndLongestEffectiveRange() can make things faster by reducing the number of potential iterations, either here or above + cfa = (uiprivCombinedFontAttr *) CFAttributedStringGetAttribute(mas, range.location, combinedFontAttrName, &range); + if (cfa != nil) { + font = [cfa toCTFontWithDefaultFont:defaultFont]; + CFAttributedStringSetAttribute(mas, range, kCTFontAttributeName, font); + CFRelease(font); + } + range.location += range.length; + } + + // and finally, get rid of all the uiprivCombinedFontAttrs as we won't need them anymore + range.location = 0; + range.length = 0; + CFAttributedStringRemoveAttribute(mas, range, combinedFontAttrName); +} + +static const CTTextAlignment ctaligns[] = { + [uiDrawTextAlignLeft] = kCTTextAlignmentLeft, + [uiDrawTextAlignCenter] = kCTTextAlignmentCenter, + [uiDrawTextAlignRight] = kCTTextAlignmentRight, +}; + +static CTParagraphStyleRef mkParagraphStyle(uiDrawTextLayoutParams *p) +{ + CTParagraphStyleRef ps; + CTParagraphStyleSetting settings[16]; + size_t nSettings = 0; + + settings[nSettings].spec = kCTParagraphStyleSpecifierAlignment; + settings[nSettings].valueSize = sizeof (CTTextAlignment); + settings[nSettings].value = ctaligns + p->Align; + nSettings++; + + ps = CTParagraphStyleCreate(settings, nSettings); + if (ps == NULL) { + // TODO + } + return ps; +} + +// TODO either rename this (on all platforms) to uiprivDrawTextLayoutParams... or rename this file or both or split the struct or something else... +CFAttributedStringRef uiprivAttributedStringToCFAttributedString(uiDrawTextLayoutParams *p, NSArray **backgroundParams) +{ + CFStringRef cfstr; + CFMutableDictionaryRef defaultAttrs; + CTParagraphStyleRef ps; + CFAttributedStringRef base; + CFMutableAttributedStringRef mas; + struct foreachParams fep; + + cfstr = CFStringCreateWithCharacters(NULL, uiprivAttributedStringUTF16String(p->String), uiprivAttributedStringUTF16Len(p->String)); + if (cfstr == NULL) { + // TODO + } + defaultAttrs = CFDictionaryCreateMutable(NULL, 0, + &kCFCopyStringDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + if (defaultAttrs == NULL) { + // TODO + } +#if 0 /* TODO */ + ffp.desc = *(p->DefaultFont); + defaultCTFont = fontdescToCTFont(&ffp); + CFDictionaryAddValue(defaultAttrs, kCTFontAttributeName, defaultCTFont); + CFRelease(defaultCTFont); +#endif + ps = mkParagraphStyle(p); + CFDictionaryAddValue(defaultAttrs, kCTParagraphStyleAttributeName, ps); + CFRelease(ps); + + base = CFAttributedStringCreate(NULL, cfstr, defaultAttrs); + if (base == NULL) { + // TODO + } + CFRelease(cfstr); + CFRelease(defaultAttrs); + mas = CFAttributedStringCreateMutableCopy(NULL, 0, base); + CFRelease(base); + + CFAttributedStringBeginEditing(mas); + fep.mas = mas; + fep.backgroundParams = [NSMutableArray new]; + uiAttributedStringForEachAttribute(p->String, processAttribute, &fep); + applyFontAttributes(mas, p->DefaultFont); + CFAttributedStringEndEditing(mas); + + *backgroundParams = fep.backgroundParams; + return mas; +} diff --git a/dep/libui/darwin/autolayout.m b/dep/libui/darwin/autolayout.m new file mode 100644 index 0000000..6bc5ce8 --- /dev/null +++ b/dep/libui/darwin/autolayout.m @@ -0,0 +1,159 @@ +// 15 august 2015 +#import "uipriv_darwin.h" + +NSLayoutConstraint *uiprivMkConstraint(id view1, NSLayoutAttribute attr1, NSLayoutRelation relation, id view2, NSLayoutAttribute attr2, CGFloat multiplier, CGFloat c, NSString *desc) +{ + NSLayoutConstraint *constraint; + + constraint = [NSLayoutConstraint constraintWithItem:view1 + attribute:attr1 + relatedBy:relation + toItem:view2 + attribute:attr2 + multiplier:multiplier + constant:c]; + uiprivFUTURE_NSLayoutConstraint_setIdentifier(constraint, desc); + return constraint; +} + +CGFloat uiDarwinMarginAmount(void *reserved) +{ + return 20.0; +} + +CGFloat uiDarwinPaddingAmount(void *reserved) +{ + return 8.0; +} + +// this is needed for NSSplitView to work properly; see http://stackoverflow.com/questions/34574478/how-can-i-set-the-position-of-a-nssplitview-nowadays-setpositionofdivideratind (stal in irc.freenode.net/#macdev came up with the exact combination) +// turns out it also works on NSTabView and NSBox too, possibly others! +// and for bonus points, it even seems to fix unsatisfiable-constraint-autoresizing-mask issues with NSTabView and NSBox too!!! this is nuts +void uiprivJiggleViewLayout(NSView *view) +{ + [view setNeedsLayout:YES]; + [view layoutSubtreeIfNeeded]; +} + +static CGFloat margins(int margined) +{ + if (!margined) + return 0.0; + return uiDarwinMarginAmount(NULL); +} + +void uiprivSingleChildConstraintsEstablish(uiprivSingleChildConstraints *c, NSView *contentView, NSView *childView, BOOL hugsTrailing, BOOL hugsBottom, int margined, NSString *desc) +{ + CGFloat margin; + + margin = margins(margined); + + c->leadingConstraint = uiprivMkConstraint(contentView, NSLayoutAttributeLeading, + NSLayoutRelationEqual, + childView, NSLayoutAttributeLeading, + 1, -margin, + [desc stringByAppendingString:@" leading constraint"]); + [contentView addConstraint:c->leadingConstraint]; + [c->leadingConstraint retain]; + + c->topConstraint = uiprivMkConstraint(contentView, NSLayoutAttributeTop, + NSLayoutRelationEqual, + childView, NSLayoutAttributeTop, + 1, -margin, + [desc stringByAppendingString:@" top constraint"]); + [contentView addConstraint:c->topConstraint]; + [c->topConstraint retain]; + + c->trailingConstraintGreater = uiprivMkConstraint(contentView, NSLayoutAttributeTrailing, + NSLayoutRelationGreaterThanOrEqual, + childView, NSLayoutAttributeTrailing, + 1, margin, + [desc stringByAppendingString:@" trailing >= constraint"]); + if (hugsTrailing) + [c->trailingConstraintGreater setPriority:NSLayoutPriorityDefaultLow]; + [contentView addConstraint:c->trailingConstraintGreater]; + [c->trailingConstraintGreater retain]; + + c->trailingConstraintEqual = uiprivMkConstraint(contentView, NSLayoutAttributeTrailing, + NSLayoutRelationEqual, + childView, NSLayoutAttributeTrailing, + 1, margin, + [desc stringByAppendingString:@" trailing == constraint"]); + if (!hugsTrailing) + [c->trailingConstraintEqual setPriority:NSLayoutPriorityDefaultLow]; + [contentView addConstraint:c->trailingConstraintEqual]; + [c->trailingConstraintEqual retain]; + + c->bottomConstraintGreater = uiprivMkConstraint(contentView, NSLayoutAttributeBottom, + NSLayoutRelationGreaterThanOrEqual, + childView, NSLayoutAttributeBottom, + 1, margin, + [desc stringByAppendingString:@" bottom >= constraint"]); + if (hugsBottom) + [c->bottomConstraintGreater setPriority:NSLayoutPriorityDefaultLow]; + [contentView addConstraint:c->bottomConstraintGreater]; + [c->bottomConstraintGreater retain]; + + c->bottomConstraintEqual = uiprivMkConstraint(contentView, NSLayoutAttributeBottom, + NSLayoutRelationEqual, + childView, NSLayoutAttributeBottom, + 1, margin, + [desc stringByAppendingString:@" bottom == constraint"]); + if (!hugsBottom) + [c->bottomConstraintEqual setPriority:NSLayoutPriorityDefaultLow]; + [contentView addConstraint:c->bottomConstraintEqual]; + [c->bottomConstraintEqual retain]; +} + +void uiprivSingleChildConstraintsRemove(uiprivSingleChildConstraints *c, NSView *cv) +{ + if (c->leadingConstraint != nil) { + [cv removeConstraint:c->leadingConstraint]; + [c->leadingConstraint release]; + c->leadingConstraint = nil; + } + if (c->topConstraint != nil) { + [cv removeConstraint:c->topConstraint]; + [c->topConstraint release]; + c->topConstraint = nil; + } + if (c->trailingConstraintGreater != nil) { + [cv removeConstraint:c->trailingConstraintGreater]; + [c->trailingConstraintGreater release]; + c->trailingConstraintGreater = nil; + } + if (c->trailingConstraintEqual != nil) { + [cv removeConstraint:c->trailingConstraintEqual]; + [c->trailingConstraintEqual release]; + c->trailingConstraintEqual = nil; + } + if (c->bottomConstraintGreater != nil) { + [cv removeConstraint:c->bottomConstraintGreater]; + [c->bottomConstraintGreater release]; + c->bottomConstraintGreater = nil; + } + if (c->bottomConstraintEqual != nil) { + [cv removeConstraint:c->bottomConstraintEqual]; + [c->bottomConstraintEqual release]; + c->bottomConstraintEqual = nil; + } +} + +void uiprivSingleChildConstraintsSetMargined(uiprivSingleChildConstraints *c, int margined) +{ + CGFloat margin; + + margin = margins(margined); + if (c->leadingConstraint != nil) + [c->leadingConstraint setConstant:-margin]; + if (c->topConstraint != nil) + [c->topConstraint setConstant:-margin]; + if (c->trailingConstraintGreater != nil) + [c->trailingConstraintGreater setConstant:margin]; + if (c->trailingConstraintEqual != nil) + [c->trailingConstraintEqual setConstant:margin]; + if (c->bottomConstraintGreater != nil) + [c->bottomConstraintGreater setConstant:margin]; + if (c->bottomConstraintEqual != nil) + [c->bottomConstraintEqual setConstant:margin]; +} diff --git a/dep/libui/darwin/box.m b/dep/libui/darwin/box.m new file mode 100644 index 0000000..72b5a71 --- /dev/null +++ b/dep/libui/darwin/box.m @@ -0,0 +1,469 @@ +// 15 august 2015 +#import "uipriv_darwin.h" + +// TODO hiding all stretchy controls still hugs trailing edge + +@interface boxChild : NSObject +@property uiControl *c; +@property BOOL stretchy; +@property NSLayoutPriority oldPrimaryHuggingPri; +@property NSLayoutPriority oldSecondaryHuggingPri; +- (NSView *)view; +@end + +@interface boxView : NSView { + uiBox *b; + NSMutableArray *children; + BOOL vertical; + int padded; + + NSLayoutConstraint *first; + NSMutableArray *inBetweens; + NSLayoutConstraint *last; + NSMutableArray *otherConstraints; + + NSLayoutAttribute primaryStart; + NSLayoutAttribute primaryEnd; + NSLayoutAttribute secondaryStart; + NSLayoutAttribute secondaryEnd; + NSLayoutAttribute primarySize; + NSLayoutConstraintOrientation primaryOrientation; + NSLayoutConstraintOrientation secondaryOrientation; +} +- (id)initWithVertical:(BOOL)vert b:(uiBox *)bb; +- (void)onDestroy; +- (void)removeOurConstraints; +- (void)syncEnableStates:(int)enabled; +- (CGFloat)paddingAmount; +- (void)establishOurConstraints; +- (void)append:(uiControl *)c stretchy:(int)stretchy; +- (void)delete:(int)n; +- (int)isPadded; +- (void)setPadded:(int)p; +- (BOOL)hugsTrailing; +- (BOOL)hugsBottom; +- (int)nStretchy; +@end + +struct uiBox { + uiDarwinControl c; + boxView *view; +}; + +@implementation boxChild + +- (NSView *)view +{ + return (NSView *) uiControlHandle(self.c); +} + +@end + +@implementation boxView + +- (id)initWithVertical:(BOOL)vert b:(uiBox *)bb +{ + self = [super initWithFrame:NSZeroRect]; + if (self != nil) { + // the weird names vert and bb are to shut the compiler up about shadowing because implicit this/self is stupid + self->b = bb; + self->vertical = vert; + self->padded = 0; + self->children = [NSMutableArray new]; + + self->inBetweens = [NSMutableArray new]; + self->otherConstraints = [NSMutableArray new]; + + if (self->vertical) { + self->primaryStart = NSLayoutAttributeTop; + self->primaryEnd = NSLayoutAttributeBottom; + self->secondaryStart = NSLayoutAttributeLeading; + self->secondaryEnd = NSLayoutAttributeTrailing; + self->primarySize = NSLayoutAttributeHeight; + self->primaryOrientation = NSLayoutConstraintOrientationVertical; + self->secondaryOrientation = NSLayoutConstraintOrientationHorizontal; + } else { + self->primaryStart = NSLayoutAttributeLeading; + self->primaryEnd = NSLayoutAttributeTrailing; + self->secondaryStart = NSLayoutAttributeTop; + self->secondaryEnd = NSLayoutAttributeBottom; + self->primarySize = NSLayoutAttributeWidth; + self->primaryOrientation = NSLayoutConstraintOrientationHorizontal; + self->secondaryOrientation = NSLayoutConstraintOrientationVertical; + } + } + return self; +} + +- (void)onDestroy +{ + boxChild *bc; + + [self removeOurConstraints]; + [self->inBetweens release]; + [self->otherConstraints release]; + + for (bc in self->children) { + uiControlSetParent(bc.c, NULL); + uiDarwinControlSetSuperview(uiDarwinControl(bc.c), nil); + uiControlDestroy(bc.c); + } + [self->children release]; +} + +- (void)removeOurConstraints +{ + if (self->first != nil) { + [self removeConstraint:self->first]; + [self->first release]; + self->first = nil; + } + if ([self->inBetweens count] != 0) { + [self removeConstraints:self->inBetweens]; + [self->inBetweens removeAllObjects]; + } + if (self->last != nil) { + [self removeConstraint:self->last]; + [self->last release]; + self->last = nil; + } + if ([self->otherConstraints count] != 0) { + [self removeConstraints:self->otherConstraints]; + [self->otherConstraints removeAllObjects]; + } +} + +- (void)syncEnableStates:(int)enabled +{ + boxChild *bc; + + for (bc in self->children) + uiDarwinControlSyncEnableState(uiDarwinControl(bc.c), enabled); +} + +- (CGFloat)paddingAmount +{ + if (!self->padded) + return 0.0; + return uiDarwinPaddingAmount(NULL); +} + +- (void)establishOurConstraints +{ + boxChild *bc; + CGFloat padding; + NSView *prev; + NSLayoutConstraint *c; + BOOL (*hugsSecondary)(uiDarwinControl *); + + [self removeOurConstraints]; + if ([self->children count] == 0) + return; + padding = [self paddingAmount]; + + // first arrange in the primary direction + prev = nil; + for (bc in self->children) { + if (!uiControlVisible(bc.c)) + continue; + if (prev == nil) { // first view + self->first = uiprivMkConstraint(self, self->primaryStart, + NSLayoutRelationEqual, + [bc view], self->primaryStart, + 1, 0, + @"uiBox first primary constraint"); + [self addConstraint:self->first]; + [self->first retain]; + prev = [bc view]; + continue; + } + // not the first; link it + c = uiprivMkConstraint(prev, self->primaryEnd, + NSLayoutRelationEqual, + [bc view], self->primaryStart, + 1, -padding, + @"uiBox in-between primary constraint"); + [self addConstraint:c]; + [self->inBetweens addObject:c]; + prev = [bc view]; + } + if (prev == nil) // no control visible; act as if no controls + return; + self->last = uiprivMkConstraint(prev, self->primaryEnd, + NSLayoutRelationEqual, + self, self->primaryEnd, + 1, 0, + @"uiBox last primary constraint"); + [self addConstraint:self->last]; + [self->last retain]; + + // then arrange in the secondary direction + hugsSecondary = uiDarwinControlHugsTrailingEdge; + if (!self->vertical) + hugsSecondary = uiDarwinControlHugsBottom; + for (bc in self->children) { + if (!uiControlVisible(bc.c)) + continue; + c = uiprivMkConstraint(self, self->secondaryStart, + NSLayoutRelationEqual, + [bc view], self->secondaryStart, + 1, 0, + @"uiBox secondary start constraint"); + [self addConstraint:c]; + [self->otherConstraints addObject:c]; + c = uiprivMkConstraint([bc view], self->secondaryEnd, + NSLayoutRelationLessThanOrEqual, + self, self->secondaryEnd, + 1, 0, + @"uiBox secondary end <= constraint"); + if ((*hugsSecondary)(uiDarwinControl(bc.c))) + [c setPriority:NSLayoutPriorityDefaultLow]; + [self addConstraint:c]; + [self->otherConstraints addObject:c]; + c = uiprivMkConstraint([bc view], self->secondaryEnd, + NSLayoutRelationEqual, + self, self->secondaryEnd, + 1, 0, + @"uiBox secondary end == constraint"); + if (!(*hugsSecondary)(uiDarwinControl(bc.c))) + [c setPriority:NSLayoutPriorityDefaultLow]; + [self addConstraint:c]; + [self->otherConstraints addObject:c]; + } + + // and make all stretchy controls the same size + if ([self nStretchy] == 0) + return; + prev = nil; // first stretchy view + for (bc in self->children) { + if (!uiControlVisible(bc.c)) + continue; + if (!bc.stretchy) + continue; + if (prev == nil) { + prev = [bc view]; + continue; + } + c = uiprivMkConstraint(prev, self->primarySize, + NSLayoutRelationEqual, + [bc view], self->primarySize, + 1, 0, + @"uiBox stretchy size constraint"); + [self addConstraint:c]; + [self->otherConstraints addObject:c]; + } +} + +- (void)append:(uiControl *)c stretchy:(int)stretchy +{ + boxChild *bc; + NSLayoutPriority priority; + int oldnStretchy; + + bc = [boxChild new]; + bc.c = c; + bc.stretchy = stretchy; + bc.oldPrimaryHuggingPri = uiDarwinControlHuggingPriority(uiDarwinControl(bc.c), self->primaryOrientation); + bc.oldSecondaryHuggingPri = uiDarwinControlHuggingPriority(uiDarwinControl(bc.c), self->secondaryOrientation); + + uiControlSetParent(bc.c, uiControl(self->b)); + uiDarwinControlSetSuperview(uiDarwinControl(bc.c), self); + uiDarwinControlSyncEnableState(uiDarwinControl(bc.c), uiControlEnabledToUser(uiControl(self->b))); + + // if a control is stretchy, it should not hug in the primary direction + // otherwise, it should *forcibly* hug + if (bc.stretchy) + priority = NSLayoutPriorityDefaultLow; + else + // LONGTERM will default high work? + priority = NSLayoutPriorityRequired; + uiDarwinControlSetHuggingPriority(uiDarwinControl(bc.c), priority, self->primaryOrientation); + // make sure controls don't hug their secondary direction so they fill the width of the view + uiDarwinControlSetHuggingPriority(uiDarwinControl(bc.c), NSLayoutPriorityDefaultLow, self->secondaryOrientation); + + oldnStretchy = [self nStretchy]; + [self->children addObject:bc]; + + [self establishOurConstraints]; + if (bc.stretchy) + if (oldnStretchy == 0) + uiDarwinNotifyEdgeHuggingChanged(uiDarwinControl(self->b)); + + [bc release]; // we don't need the initial reference now +} + +- (void)delete:(int)n +{ + boxChild *bc; + int stretchy; + + bc = (boxChild *) [self->children objectAtIndex:n]; + stretchy = bc.stretchy; + + uiControlSetParent(bc.c, NULL); + uiDarwinControlSetSuperview(uiDarwinControl(bc.c), nil); + + uiDarwinControlSetHuggingPriority(uiDarwinControl(bc.c), bc.oldPrimaryHuggingPri, self->primaryOrientation); + uiDarwinControlSetHuggingPriority(uiDarwinControl(bc.c), bc.oldSecondaryHuggingPri, self->secondaryOrientation); + + [self->children removeObjectAtIndex:n]; + + [self establishOurConstraints]; + if (stretchy) + if ([self nStretchy] == 0) + uiDarwinNotifyEdgeHuggingChanged(uiDarwinControl(self->b)); +} + +- (int)isPadded +{ + return self->padded; +} + +- (void)setPadded:(int)p +{ + CGFloat padding; + NSLayoutConstraint *c; + + self->padded = p; + padding = [self paddingAmount]; + for (c in self->inBetweens) + [c setConstant:-padding]; +} + +- (BOOL)hugsTrailing +{ + if (self->vertical) // always hug if vertical + return YES; + return [self nStretchy] != 0; +} + +- (BOOL)hugsBottom +{ + if (!self->vertical) // always hug if horizontal + return YES; + return [self nStretchy] != 0; +} + +- (int)nStretchy +{ + boxChild *bc; + int n; + + n = 0; + for (bc in self->children) { + if (!uiControlVisible(bc.c)) + continue; + if (bc.stretchy) + n++; + } + return n; +} + +@end + +static void uiBoxDestroy(uiControl *c) +{ + uiBox *b = uiBox(c); + + [b->view onDestroy]; + [b->view release]; + uiFreeControl(uiControl(b)); +} + +uiDarwinControlDefaultHandle(uiBox, view) +uiDarwinControlDefaultParent(uiBox, view) +uiDarwinControlDefaultSetParent(uiBox, view) +uiDarwinControlDefaultToplevel(uiBox, view) +uiDarwinControlDefaultVisible(uiBox, view) +uiDarwinControlDefaultShow(uiBox, view) +uiDarwinControlDefaultHide(uiBox, view) +uiDarwinControlDefaultEnabled(uiBox, view) +uiDarwinControlDefaultEnable(uiBox, view) +uiDarwinControlDefaultDisable(uiBox, view) + +static void uiBoxSyncEnableState(uiDarwinControl *c, int enabled) +{ + uiBox *b = uiBox(c); + + if (uiDarwinShouldStopSyncEnableState(uiDarwinControl(b), enabled)) + return; + [b->view syncEnableStates:enabled]; +} + +uiDarwinControlDefaultSetSuperview(uiBox, view) + +static BOOL uiBoxHugsTrailingEdge(uiDarwinControl *c) +{ + uiBox *b = uiBox(c); + + return [b->view hugsTrailing]; +} + +static BOOL uiBoxHugsBottom(uiDarwinControl *c) +{ + uiBox *b = uiBox(c); + + return [b->view hugsBottom]; +} + +static void uiBoxChildEdgeHuggingChanged(uiDarwinControl *c) +{ + uiBox *b = uiBox(c); + + [b->view establishOurConstraints]; +} + +uiDarwinControlDefaultHuggingPriority(uiBox, view) +uiDarwinControlDefaultSetHuggingPriority(uiBox, view) + +static void uiBoxChildVisibilityChanged(uiDarwinControl *c) +{ + uiBox *b = uiBox(c); + + [b->view establishOurConstraints]; +} + +void uiBoxAppend(uiBox *b, uiControl *c, int stretchy) +{ + // LONGTERM on other platforms + // or at leat allow this and implicitly turn it into a spacer + if (c == NULL) + uiprivUserBug("You cannot add NULL to a uiBox."); + [b->view append:c stretchy:stretchy]; +} + +void uiBoxDelete(uiBox *b, int n) +{ + [b->view delete:n]; +} + +int uiBoxPadded(uiBox *b) +{ + return [b->view isPadded]; +} + +void uiBoxSetPadded(uiBox *b, int padded) +{ + [b->view setPadded:padded]; +} + +static uiBox *finishNewBox(BOOL vertical) +{ + uiBox *b; + + uiDarwinNewControl(uiBox, b); + + b->view = [[boxView alloc] initWithVertical:vertical b:b]; + + return b; +} + +uiBox *uiNewHorizontalBox(void) +{ + return finishNewBox(NO); +} + +uiBox *uiNewVerticalBox(void) +{ + return finishNewBox(YES); +} diff --git a/dep/libui/darwin/button.m b/dep/libui/darwin/button.m new file mode 100644 index 0000000..c3a6e07 --- /dev/null +++ b/dep/libui/darwin/button.m @@ -0,0 +1,113 @@ +// 13 august 2015 +#import "uipriv_darwin.h" + +struct uiButton { + uiDarwinControl c; + NSButton *button; + void (*onClicked)(uiButton *, void *); + void *onClickedData; +}; + +@interface buttonDelegateClass : NSObject { + uiprivMap *buttons; +} +- (IBAction)onClicked:(id)sender; +- (void)registerButton:(uiButton *)b; +- (void)unregisterButton:(uiButton *)b; +@end + +@implementation buttonDelegateClass + +- (id)init +{ + self = [super init]; + if (self) + self->buttons = uiprivNewMap(); + return self; +} + +- (void)dealloc +{ + uiprivMapDestroy(self->buttons); + [super dealloc]; +} + +- (IBAction)onClicked:(id)sender +{ + uiButton *b; + + b = (uiButton *) uiprivMapGet(self->buttons, sender); + (*(b->onClicked))(b, b->onClickedData); +} + +- (void)registerButton:(uiButton *)b +{ + uiprivMapSet(self->buttons, b->button, b); + [b->button setTarget:self]; + [b->button setAction:@selector(onClicked:)]; +} + +- (void)unregisterButton:(uiButton *)b +{ + [b->button setTarget:nil]; + uiprivMapDelete(self->buttons, b->button); +} + +@end + +static buttonDelegateClass *buttonDelegate = nil; + +uiDarwinControlAllDefaultsExceptDestroy(uiButton, button) + +static void uiButtonDestroy(uiControl *c) +{ + uiButton *b = uiButton(c); + + [buttonDelegate unregisterButton:b]; + [b->button release]; + uiFreeControl(uiControl(b)); +} + +char *uiButtonText(uiButton *b) +{ + return uiDarwinNSStringToText([b->button title]); +} + +void uiButtonSetText(uiButton *b, const char *text) +{ + [b->button setTitle:uiprivToNSString(text)]; +} + +void uiButtonOnClicked(uiButton *b, void (*f)(uiButton *, void *), void *data) +{ + b->onClicked = f; + b->onClickedData = data; +} + +static void defaultOnClicked(uiButton *b, void *data) +{ + // do nothing +} + +uiButton *uiNewButton(const char *text) +{ + uiButton *b; + + uiDarwinNewControl(uiButton, b); + + b->button = [[NSButton alloc] initWithFrame:NSZeroRect]; + [b->button setTitle:uiprivToNSString(text)]; + [b->button setButtonType:NSMomentaryPushInButton]; + [b->button setBordered:YES]; + [b->button setBezelStyle:NSRoundedBezelStyle]; + uiDarwinSetControlFont(b->button, NSRegularControlSize); + + if (buttonDelegate == nil) { + buttonDelegate = [[buttonDelegateClass new] autorelease]; + [uiprivDelegates addObject:buttonDelegate]; + } + [buttonDelegate registerButton:b]; + uiButtonOnClicked(b, defaultOnClicked, NULL); + + return b; +} diff --git a/dep/libui/darwin/checkbox.m b/dep/libui/darwin/checkbox.m new file mode 100644 index 0000000..d5a3d6e --- /dev/null +++ b/dep/libui/darwin/checkbox.m @@ -0,0 +1,129 @@ +// 14 august 2015 +#import "uipriv_darwin.h" + +struct uiCheckbox { + uiDarwinControl c; + NSButton *button; + void (*onToggled)(uiCheckbox *, void *); + void *onToggledData; +}; + +@interface checkboxDelegateClass : NSObject { + uiprivMap *buttons; +} +- (IBAction)onToggled:(id)sender; +- (void)registerCheckbox:(uiCheckbox *)c; +- (void)unregisterCheckbox:(uiCheckbox *)c; +@end + +@implementation checkboxDelegateClass + +- (id)init +{ + self = [super init]; + if (self) + self->buttons = uiprivNewMap(); + return self; +} + +- (void)dealloc +{ + uiprivMapDestroy(self->buttons); + [super dealloc]; +} + +- (IBAction)onToggled:(id)sender +{ + uiCheckbox *c; + + c = (uiCheckbox *) uiprivMapGet(self->buttons, sender); + (*(c->onToggled))(c, c->onToggledData); +} + +- (void)registerCheckbox:(uiCheckbox *)c +{ + uiprivMapSet(self->buttons, c->button, c); + [c->button setTarget:self]; + [c->button setAction:@selector(onToggled:)]; +} + +- (void)unregisterCheckbox:(uiCheckbox *)c +{ + [c->button setTarget:nil]; + uiprivMapDelete(self->buttons, c->button); +} + +@end + +static checkboxDelegateClass *checkboxDelegate = nil; + +uiDarwinControlAllDefaultsExceptDestroy(uiCheckbox, button) + +static void uiCheckboxDestroy(uiControl *cc) +{ + uiCheckbox *c = uiCheckbox(cc); + + [checkboxDelegate unregisterCheckbox:c]; + [c->button release]; + uiFreeControl(uiControl(c)); +} + +char *uiCheckboxText(uiCheckbox *c) +{ + return uiDarwinNSStringToText([c->button title]); +} + +void uiCheckboxSetText(uiCheckbox *c, const char *text) +{ + [c->button setTitle:uiprivToNSString(text)]; +} + +void uiCheckboxOnToggled(uiCheckbox *c, void (*f)(uiCheckbox *, void *), void *data) +{ + c->onToggled = f; + c->onToggledData = data; +} + +int uiCheckboxChecked(uiCheckbox *c) +{ + return [c->button state] == NSOnState; +} + +void uiCheckboxSetChecked(uiCheckbox *c, int checked) +{ + NSInteger state; + + state = NSOnState; + if (!checked) + state = NSOffState; + [c->button setState:state]; +} + +static void defaultOnToggled(uiCheckbox *c, void *data) +{ + // do nothing +} + +uiCheckbox *uiNewCheckbox(const char *text) +{ + uiCheckbox *c; + + uiDarwinNewControl(uiCheckbox, c); + + c->button = [[NSButton alloc] initWithFrame:NSZeroRect]; + [c->button setTitle:uiprivToNSString(text)]; + [c->button setButtonType:NSSwitchButton]; + // doesn't seem to have an associated bezel style + [c->button setBordered:NO]; + [c->button setTransparent:NO]; + uiDarwinSetControlFont(c->button, NSRegularControlSize); + + if (checkboxDelegate == nil) { + checkboxDelegate = [[checkboxDelegateClass new] autorelease]; + [uiprivDelegates addObject:checkboxDelegate]; + } + [checkboxDelegate registerCheckbox:c]; + uiCheckboxOnToggled(c, defaultOnToggled, NULL); + + return c; +} diff --git a/dep/libui/darwin/colorbutton.m b/dep/libui/darwin/colorbutton.m new file mode 100644 index 0000000..f2bee77 --- /dev/null +++ b/dep/libui/darwin/colorbutton.m @@ -0,0 +1,159 @@ +// 15 may 2016 +#import "uipriv_darwin.h" + +// TODO no intrinsic height? + +@interface colorButton : NSColorWell { + uiColorButton *libui_b; + BOOL libui_changing; + BOOL libui_setting; +} +- (id)initWithFrame:(NSRect)frame libuiColorButton:(uiColorButton *)b; +- (void)deactivateOnClose:(NSNotification *)note; +- (void)libuiColor:(double *)r g:(double *)g b:(double *)b a:(double *)a; +- (void)libuiSetColor:(double)r g:(double)g b:(double)b a:(double)a; +@end + +// only one may be active at one time +static colorButton *activeColorButton = nil; + +struct uiColorButton { + uiDarwinControl c; + colorButton *button; + void (*onChanged)(uiColorButton *, void *); + void *onChangedData; +}; + +@implementation colorButton + +- (id)initWithFrame:(NSRect)frame libuiColorButton:(uiColorButton *)b +{ + self = [super initWithFrame:frame]; + if (self) { + // the default color is white; set it to black first (see -setColor: below for why we do it first) + [self libuiSetColor:0.0 g:0.0 b:0.0 a:1.0]; + + self->libui_b = b; + self->libui_changing = NO; + } + return self; +} + +- (void)activate:(BOOL)exclusive +{ + if (activeColorButton != nil) + activeColorButton->libui_changing = YES; + [NSColorPanel setPickerMask:NSColorPanelAllModesMask]; + [[NSColorPanel sharedColorPanel] setShowsAlpha:YES]; + [super activate:YES]; + activeColorButton = self; + // see stddialogs.m for details + [[NSColorPanel sharedColorPanel] setWorksWhenModal:NO]; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(deactivateOnClose:) + name:NSWindowWillCloseNotification + object:[NSColorPanel sharedColorPanel]]; +} + +- (void)deactivate +{ + [super deactivate]; + activeColorButton = nil; + if (!self->libui_changing) + [[NSColorPanel sharedColorPanel] orderOut:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self + name:NSWindowWillCloseNotification + object:[NSColorPanel sharedColorPanel]]; + self->libui_changing = NO; +} + +- (void)deactivateOnClose:(NSNotification *)note +{ + [self deactivate]; +} + +- (void)setColor:(NSColor *)color +{ + uiColorButton *b = self->libui_b; + + [super setColor:color]; + // this is called by NSColorWell's init, so we have to guard + // also don't signal during a programmatic change + if (b != nil && !self->libui_setting) + (*(b->onChanged))(b, b->onChangedData); +} + +- (void)libuiColor:(double *)r g:(double *)g b:(double *)b a:(double *)a +{ + NSColor *rgba; + CGFloat cr, cg, cb, ca; + + // the given color may not be an RGBA color, which will cause the -getRed:green:blue:alpha: call to throw an exception + rgba = [[self color] colorUsingColorSpace:[NSColorSpace sRGBColorSpace]]; + [rgba getRed:&cr green:&cg blue:&cb alpha:&ca]; + *r = cr; + *g = cg; + *b = cb; + *a = ca; + // rgba will be autoreleased since it isn't a new or init call +} + +- (void)libuiSetColor:(double)r g:(double)g b:(double)b a:(double)a +{ + self->libui_setting = YES; + [self setColor:[NSColor colorWithSRGBRed:r green:g blue:b alpha:a]]; + self->libui_setting = NO; +} + +// NSColorWell has no intrinsic size by default; give it the default Interface Builder size. +- (NSSize)intrinsicContentSize +{ + return NSMakeSize(44, 23); +} + +@end + +uiDarwinControlAllDefaults(uiColorButton, button) + +// we do not want color change events to be sent to any controls other than the color buttons +// see main.m for more details +BOOL uiprivColorButtonInhibitSendAction(SEL sel, id from, id to) +{ + if (sel != @selector(changeColor:)) + return NO; + return ![to isKindOfClass:[colorButton class]]; +} + +static void defaultOnChanged(uiColorButton *b, void *data) +{ + // do nothing +} + +void uiColorButtonColor(uiColorButton *b, double *r, double *g, double *bl, double *a) +{ + [b->button libuiColor:r g:g b:bl a:a]; +} + +void uiColorButtonSetColor(uiColorButton *b, double r, double g, double bl, double a) +{ + [b->button libuiSetColor:r g:g b:bl a:a]; +} + +void uiColorButtonOnChanged(uiColorButton *b, void (*f)(uiColorButton *, void *), void *data) +{ + b->onChanged = f; + b->onChangedData = data; +} + +uiColorButton *uiNewColorButton(void) +{ + uiColorButton *b; + + uiDarwinNewControl(uiColorButton, b); + + b->button = [[colorButton alloc] initWithFrame:NSZeroRect libuiColorButton:b]; + + uiColorButtonOnChanged(b, defaultOnChanged, NULL); + + return b; +} diff --git a/dep/libui/darwin/combobox.m b/dep/libui/darwin/combobox.m new file mode 100644 index 0000000..cc2f330 --- /dev/null +++ b/dep/libui/darwin/combobox.m @@ -0,0 +1,145 @@ +// 14 august 2015 +#import "uipriv_darwin.h" + +// NSComboBoxes have no intrinsic width; we'll use the default Interface Builder width for them. +// NSPopUpButton is fine. +#define comboboxWidth 96 + +struct uiCombobox { + uiDarwinControl c; + NSPopUpButton *pb; + NSArrayController *pbac; + void (*onSelected)(uiCombobox *, void *); + void *onSelectedData; +}; + +@interface comboboxDelegateClass : NSObject { + uiprivMap *comboboxes; +} +- (IBAction)onSelected:(id)sender; +- (void)registerCombobox:(uiCombobox *)c; +- (void)unregisterCombobox:(uiCombobox *)c; +@end + +@implementation comboboxDelegateClass + +- (id)init +{ + self = [super init]; + if (self) + self->comboboxes = uiprivNewMap(); + return self; +} + +- (void)dealloc +{ + uiprivMapDestroy(self->comboboxes); + [super dealloc]; +} + +- (IBAction)onSelected:(id)sender +{ + uiCombobox *c; + + c = uiCombobox(uiprivMapGet(self->comboboxes, sender)); + (*(c->onSelected))(c, c->onSelectedData); +} + +- (void)registerCombobox:(uiCombobox *)c +{ + uiprivMapSet(self->comboboxes, c->pb, c); + [c->pb setTarget:self]; + [c->pb setAction:@selector(onSelected:)]; +} + +- (void)unregisterCombobox:(uiCombobox *)c +{ + [c->pb setTarget:nil]; + uiprivMapDelete(self->comboboxes, c->pb); +} + +@end + +static comboboxDelegateClass *comboboxDelegate = nil; + +uiDarwinControlAllDefaultsExceptDestroy(uiCombobox, pb) + +static void uiComboboxDestroy(uiControl *cc) +{ + uiCombobox *c = uiCombobox(cc); + + [comboboxDelegate unregisterCombobox:c]; + [c->pb unbind:@"contentObjects"]; + [c->pb unbind:@"selectedIndex"]; + [c->pbac release]; + [c->pb release]; + uiFreeControl(uiControl(c)); +} + +void uiComboboxAppend(uiCombobox *c, const char *text) +{ + [c->pbac addObject:uiprivToNSString(text)]; +} + +int uiComboboxSelected(uiCombobox *c) +{ + return [c->pb indexOfSelectedItem]; +} + +void uiComboboxSetSelected(uiCombobox *c, int n) +{ + [c->pb selectItemAtIndex:n]; +} + +void uiComboboxOnSelected(uiCombobox *c, void (*f)(uiCombobox *c, void *data), void *data) +{ + c->onSelected = f; + c->onSelectedData = data; +} + +static void defaultOnSelected(uiCombobox *c, void *data) +{ + // do nothing +} + +uiCombobox *uiNewCombobox(void) +{ + uiCombobox *c; + NSPopUpButtonCell *pbcell; + + uiDarwinNewControl(uiCombobox, c); + + c->pb = [[NSPopUpButton alloc] initWithFrame:NSZeroRect pullsDown:NO]; + [c->pb setPreferredEdge:NSMinYEdge]; + pbcell = (NSPopUpButtonCell *) [c->pb cell]; + [pbcell setArrowPosition:NSPopUpArrowAtBottom]; + // the font defined by Interface Builder is Menu 13, which is lol + // just use the regular control size for consistency + uiDarwinSetControlFont(c->pb, NSRegularControlSize); + + // NSPopUpButton doesn't work like a combobox + // - it automatically selects the first item + // - it doesn't support duplicates + // but we can use a NSArrayController and Cocoa bindings to bypass these restrictions + c->pbac = [NSArrayController new]; + [c->pbac setAvoidsEmptySelection:NO]; + [c->pbac setSelectsInsertedObjects:NO]; + [c->pbac setAutomaticallyRearrangesObjects:NO]; + [c->pb bind:@"contentValues" + toObject:c->pbac + withKeyPath:@"arrangedObjects" + options:nil]; + [c->pb bind:@"selectedIndex" + toObject:c->pbac + withKeyPath:@"selectionIndex" + options:nil]; + + if (comboboxDelegate == nil) { + comboboxDelegate = [[comboboxDelegateClass new] autorelease]; + [uiprivDelegates addObject:comboboxDelegate]; + } + [comboboxDelegate registerCombobox:c]; + uiComboboxOnSelected(c, defaultOnSelected, NULL); + + return c; +} diff --git a/dep/libui/darwin/control.m b/dep/libui/darwin/control.m new file mode 100644 index 0000000..9eaf47a --- /dev/null +++ b/dep/libui/darwin/control.m @@ -0,0 +1,84 @@ +// 16 august 2015 +#import "uipriv_darwin.h" + +void uiDarwinControlSyncEnableState(uiDarwinControl *c, int state) +{ + (*(c->SyncEnableState))(c, state); +} + +void uiDarwinControlSetSuperview(uiDarwinControl *c, NSView *superview) +{ + (*(c->SetSuperview))(c, superview); +} + +BOOL uiDarwinControlHugsTrailingEdge(uiDarwinControl *c) +{ + return (*(c->HugsTrailingEdge))(c); +} + +BOOL uiDarwinControlHugsBottom(uiDarwinControl *c) +{ + return (*(c->HugsBottom))(c); +} + +void uiDarwinControlChildEdgeHuggingChanged(uiDarwinControl *c) +{ + (*(c->ChildEdgeHuggingChanged))(c); +} + +NSLayoutPriority uiDarwinControlHuggingPriority(uiDarwinControl *c, NSLayoutConstraintOrientation orientation) +{ + return (*(c->HuggingPriority))(c, orientation); +} + +void uiDarwinControlSetHuggingPriority(uiDarwinControl *c, NSLayoutPriority priority, NSLayoutConstraintOrientation orientation) +{ + (*(c->SetHuggingPriority))(c, priority, orientation); +} + +void uiDarwinControlChildVisibilityChanged(uiDarwinControl *c) +{ + (*(c->ChildVisibilityChanged))(c); +} + +void uiDarwinSetControlFont(NSControl *c, NSControlSize size) +{ + [c setFont:[NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:size]]]; +} + +#define uiDarwinControlSignature 0x44617277 + +uiDarwinControl *uiDarwinAllocControl(size_t n, uint32_t typesig, const char *typenamestr) +{ + return uiDarwinControl(uiAllocControl(n, uiDarwinControlSignature, typesig, typenamestr)); +} + +BOOL uiDarwinShouldStopSyncEnableState(uiDarwinControl *c, BOOL enabled) +{ + int ce; + + ce = uiControlEnabled(uiControl(c)); + // only stop if we're going from disabled back to enabled; don't stop under any other condition + // (if we stop when going from enabled to disabled then enabled children of a disabled control won't get disabled at the OS level) + if (!ce && enabled) + return YES; + return NO; +} + +void uiDarwinNotifyEdgeHuggingChanged(uiDarwinControl *c) +{ + uiControl *parent; + + parent = uiControlParent(uiControl(c)); + if (parent != NULL) + uiDarwinControlChildEdgeHuggingChanged(uiDarwinControl(parent)); +} + +void uiDarwinNotifyVisibilityChanged(uiDarwinControl *c) +{ + uiControl *parent; + + parent = uiControlParent(uiControl(c)); + if (parent != NULL) + uiDarwinControlChildVisibilityChanged(uiDarwinControl(parent)); +} diff --git a/dep/libui/darwin/datetimepicker.m b/dep/libui/darwin/datetimepicker.m new file mode 100644 index 0000000..b786dea --- /dev/null +++ b/dep/libui/darwin/datetimepicker.m @@ -0,0 +1,172 @@ +// 14 august 2015 +#import "uipriv_darwin.h" + +struct uiDateTimePicker { + uiDarwinControl c; + NSDatePicker *dp; + void (*onChanged)(uiDateTimePicker *, void *); + void *onChangedData; + BOOL blockSendOnce; +}; + +// TODO see if target-action works here or not; I forgot what cody271@ originally said +// the primary advantage of the delegate is the ability to reject changes, but libui doesn't support that yet — we should consider that API option as well +@interface uiprivDatePickerDelegateClass : NSObject { + uiprivMap *pickers; +} +- (void)datePickerCell:(NSDatePickerCell *)aDatePickerCell validateProposedDateValue:(NSDate **)proposedDateValue timeInterval:(NSTimeInterval *)proposedTimeInterval; +- (void)doTimer:(NSTimer *)timer; +- (void)registerPicker:(uiDateTimePicker *)d; +- (void)unregisterPicker:(uiDateTimePicker *)d; +@end + +@implementation uiprivDatePickerDelegateClass + +- (id)init +{ + self = [super init]; + if (self) + self->pickers = uiprivNewMap(); + return self; +} + +- (void)dealloc +{ + uiprivMapDestroy(self->pickers); + [super dealloc]; +} + +- (void)datePickerCell:(NSDatePickerCell *)cell validateProposedDateValue:(NSDate **)proposedDateValue timeInterval:(NSTimeInterval *)proposedTimeInterval +{ + uiDateTimePicker *d; + + d = (uiDateTimePicker *) uiprivMapGet(self->pickers, cell); + [NSTimer scheduledTimerWithTimeInterval:0 + target:self + selector:@selector(doTimer:) + userInfo:[NSValue valueWithPointer:d] + repeats:NO]; +} + +- (void)doTimer:(NSTimer *)timer +{ + NSValue *v; + uiDateTimePicker *d; + + v = (NSValue *) [timer userInfo]; + d = (uiDateTimePicker *) [v pointerValue]; + if (d->blockSendOnce) { + d->blockSendOnce = NO; + return; + } + (*(d->onChanged))(d, d->onChangedData); +} + +- (void)registerPicker:(uiDateTimePicker *)d +{ + uiprivMapSet(self->pickers, d->dp.cell, d); + [d->dp setDelegate:self]; +} + +- (void)unregisterPicker:(uiDateTimePicker *)d +{ + [d->dp setDelegate:nil]; + uiprivMapDelete(self->pickers, d->dp.cell); +} + +@end + +static uiprivDatePickerDelegateClass *datePickerDelegate = nil; + +uiDarwinControlAllDefaultsExceptDestroy(uiDateTimePicker, dp) + +static void uiDateTimePickerDestroy(uiControl *c) +{ + uiDateTimePicker *d = uiDateTimePicker(c); + + [datePickerDelegate unregisterPicker:d]; + [d->dp release]; + uiFreeControl(uiControl(d)); +} + +static void defaultOnChanged(uiDateTimePicker *d, void *data) +{ + // do nothing +} + +// TODO consider using NSDateComponents iff we ever need the extra accuracy of not using NSTimeInterval +void uiDateTimePickerTime(uiDateTimePicker *d, struct tm *time) +{ + time_t t; + struct tm tmbuf; + NSDate *date; + + date = [d->dp dateValue]; + t = (time_t) [date timeIntervalSince1970]; + + // Copy time to minimize a race condition + // time.h functions use global non-thread-safe data + tmbuf = *localtime(&t); + memcpy(time, &tmbuf, sizeof (struct tm)); +} + +void uiDateTimePickerSetTime(uiDateTimePicker *d, const struct tm *time) +{ + time_t t; + struct tm tmbuf; + + // Copy time because mktime() modifies its argument + memcpy(&tmbuf, time, sizeof (struct tm)); + t = mktime(&tmbuf); + + // TODO get rid of the need for this + d->blockSendOnce = YES; + [d->dp setDateValue:[NSDate dateWithTimeIntervalSince1970:t]]; +} + +void uiDateTimePickerOnChanged(uiDateTimePicker *d, void (*f)(uiDateTimePicker *, void *), void *data) +{ + d->onChanged = f; + d->onChangedData = data; +} + +static uiDateTimePicker *finishNewDateTimePicker(NSDatePickerElementFlags elements) +{ + uiDateTimePicker *d; + + uiDarwinNewControl(uiDateTimePicker, d); + + d->dp = [[NSDatePicker alloc] initWithFrame:NSZeroRect]; + [d->dp setDateValue:[NSDate date]]; + [d->dp setBordered:NO]; + [d->dp setBezeled:YES]; + [d->dp setDrawsBackground:YES]; + [d->dp setDatePickerStyle:NSTextFieldAndStepperDatePickerStyle]; + [d->dp setDatePickerElements:elements]; + [d->dp setDatePickerMode:NSSingleDateMode]; + uiDarwinSetControlFont(d->dp, NSRegularControlSize); + + if (datePickerDelegate == nil) { + datePickerDelegate = [[uiprivDatePickerDelegateClass new] autorelease]; + [uiprivDelegates addObject:datePickerDelegate]; + } + [datePickerDelegate registerPicker:d]; + uiDateTimePickerOnChanged(d, defaultOnChanged, NULL); + + return d; +} + +uiDateTimePicker *uiNewDateTimePicker(void) +{ + return finishNewDateTimePicker(NSYearMonthDayDatePickerElementFlag | NSHourMinuteSecondDatePickerElementFlag); +} + +uiDateTimePicker *uiNewDatePicker(void) +{ + return finishNewDateTimePicker(NSYearMonthDayDatePickerElementFlag); +} + +uiDateTimePicker *uiNewTimePicker(void) +{ + return finishNewDateTimePicker(NSHourMinuteSecondDatePickerElementFlag); +} diff --git a/dep/libui/darwin/debug.m b/dep/libui/darwin/debug.m new file mode 100644 index 0000000..aff66e0 --- /dev/null +++ b/dep/libui/darwin/debug.m @@ -0,0 +1,19 @@ +// 13 may 2016 +#import "uipriv_darwin.h" + +// LONGTERM don't halt on release builds + +void uiprivRealBug(const char *file, const char *line, const char *func, const char *prefix, const char *format, va_list ap) +{ + NSMutableString *str; + NSString *formatted; + + str = [NSMutableString new]; + [str appendString:[NSString stringWithFormat:@"[libui] %s:%s:%s() %s", file, line, func, prefix]]; + formatted = [[NSString alloc] initWithFormat:[NSString stringWithUTF8String:format] arguments:ap]; + [str appendString:formatted]; + [formatted release]; + NSLog(@"%@", str); + [str release]; + __builtin_trap(); +} diff --git a/dep/libui/darwin/draw.h b/dep/libui/darwin/draw.h new file mode 100644 index 0000000..382b7e7 --- /dev/null +++ b/dep/libui/darwin/draw.h @@ -0,0 +1,8 @@ +// 6 january 2017 + +// TODO why do we still have this file; should we just split draw.m or not + +struct uiDrawContext { + CGContextRef c; + CGFloat height; // needed for text; see below +}; diff --git a/dep/libui/darwin/draw.m b/dep/libui/darwin/draw.m new file mode 100644 index 0000000..e54ecdd --- /dev/null +++ b/dep/libui/darwin/draw.m @@ -0,0 +1,449 @@ +// 6 september 2015 +#import "uipriv_darwin.h" +#import "draw.h" + +struct uiDrawPath { + CGMutablePathRef path; + uiDrawFillMode fillMode; + BOOL ended; +}; + +uiDrawPath *uiDrawNewPath(uiDrawFillMode mode) +{ + uiDrawPath *p; + + p = uiprivNew(uiDrawPath); + p->path = CGPathCreateMutable(); + p->fillMode = mode; + return p; +} + +void uiDrawFreePath(uiDrawPath *p) +{ + CGPathRelease((CGPathRef) (p->path)); + uiprivFree(p); +} + +void uiDrawPathNewFigure(uiDrawPath *p, double x, double y) +{ + if (p->ended) + uiprivUserBug("You cannot call uiDrawPathNewFigure() on a uiDrawPath that has already been ended. (path; %p)", p); + CGPathMoveToPoint(p->path, NULL, x, y); +} + +void uiDrawPathNewFigureWithArc(uiDrawPath *p, double xCenter, double yCenter, double radius, double startAngle, double sweep, int negative) +{ + double sinStart, cosStart; + double startx, starty; + + if (p->ended) + uiprivUserBug("You cannot call uiDrawPathNewFigureWithArc() on a uiDrawPath that has already been ended. (path; %p)", p); + sinStart = sin(startAngle); + cosStart = cos(startAngle); + startx = xCenter + radius * cosStart; + starty = yCenter + radius * sinStart; + CGPathMoveToPoint(p->path, NULL, startx, starty); + uiDrawPathArcTo(p, xCenter, yCenter, radius, startAngle, sweep, negative); +} + +void uiDrawPathLineTo(uiDrawPath *p, double x, double y) +{ + // TODO refine this to require being in a path + if (p->ended) + uiprivImplBug("attempt to add line to ended path in uiDrawPathLineTo()"); + CGPathAddLineToPoint(p->path, NULL, x, y); +} + +void uiDrawPathArcTo(uiDrawPath *p, double xCenter, double yCenter, double radius, double startAngle, double sweep, int negative) +{ + bool cw; + + // TODO likewise + if (p->ended) + uiprivImplBug("attempt to add arc to ended path in uiDrawPathArcTo()"); + if (sweep > 2 * uiPi) + sweep = 2 * uiPi; + cw = false; + if (negative) + cw = true; + CGPathAddArc(p->path, NULL, + xCenter, yCenter, + radius, + startAngle, startAngle + sweep, + cw); +} + +void uiDrawPathBezierTo(uiDrawPath *p, double c1x, double c1y, double c2x, double c2y, double endX, double endY) +{ + // TODO likewise + if (p->ended) + uiprivImplBug("attempt to add bezier to ended path in uiDrawPathBezierTo()"); + CGPathAddCurveToPoint(p->path, NULL, + c1x, c1y, + c2x, c2y, + endX, endY); +} + +void uiDrawPathCloseFigure(uiDrawPath *p) +{ + // TODO likewise + if (p->ended) + uiprivImplBug("attempt to close figure of ended path in uiDrawPathCloseFigure()"); + CGPathCloseSubpath(p->path); +} + +void uiDrawPathAddRectangle(uiDrawPath *p, double x, double y, double width, double height) +{ + if (p->ended) + uiprivUserBug("You cannot call uiDrawPathAddRectangle() on a uiDrawPath that has already been ended. (path; %p)", p); + CGPathAddRect(p->path, NULL, CGRectMake(x, y, width, height)); +} + +void uiDrawPathEnd(uiDrawPath *p) +{ + p->ended = TRUE; +} + +uiDrawContext *uiprivDrawNewContext(CGContextRef ctxt, CGFloat height) +{ + uiDrawContext *c; + + c = uiprivNew(uiDrawContext); + c->c = ctxt; + c->height = height; + return c; +} + +void uiprivDrawFreeContext(uiDrawContext *c) +{ + uiprivFree(c); +} + +// a stroke is identical to a fill of a stroked path +// we need to do this in order to stroke with a gradient; see http://stackoverflow.com/a/25034854/3408572 +// doing this for other brushes works too +void uiDrawStroke(uiDrawContext *c, uiDrawPath *path, uiDrawBrush *b, uiDrawStrokeParams *p) +{ + CGLineCap cap; + CGLineJoin join; + CGPathRef dashPath; + CGFloat *dashes; + size_t i; + uiDrawPath p2; + + if (!path->ended) + uiprivUserBug("You cannot call uiDrawStroke() on a uiDrawPath that has not been ended. (path: %p)", path); + + switch (p->Cap) { + case uiDrawLineCapFlat: + cap = kCGLineCapButt; + break; + case uiDrawLineCapRound: + cap = kCGLineCapRound; + break; + case uiDrawLineCapSquare: + cap = kCGLineCapSquare; + break; + } + switch (p->Join) { + case uiDrawLineJoinMiter: + join = kCGLineJoinMiter; + break; + case uiDrawLineJoinRound: + join = kCGLineJoinRound; + break; + case uiDrawLineJoinBevel: + join = kCGLineJoinBevel; + break; + } + + // create a temporary path identical to the previous one + dashPath = (CGPathRef) path->path; + if (p->NumDashes != 0) { + dashes = (CGFloat *) uiprivAlloc(p->NumDashes * sizeof (CGFloat), "CGFloat[]"); + for (i = 0; i < p->NumDashes; i++) + dashes[i] = p->Dashes[i]; + dashPath = CGPathCreateCopyByDashingPath(path->path, + NULL, + p->DashPhase, + dashes, + p->NumDashes); + uiprivFree(dashes); + } + // the documentation is wrong: this produces a path suitable for calling CGPathCreateCopyByStrokingPath(), not for filling directly + // the cast is safe; we never modify the CGPathRef and always cast it back to a CGPathRef anyway + p2.path = (CGMutablePathRef) CGPathCreateCopyByStrokingPath(dashPath, + NULL, + p->Thickness, + cap, + join, + p->MiterLimit); + if (p->NumDashes != 0) + CGPathRelease(dashPath); + + // always draw stroke fills using the winding rule + // otherwise intersecting figures won't draw correctly + p2.fillMode = uiDrawFillModeWinding; + p2.ended = path->ended; + uiDrawFill(c, &p2, b); + // and clean up + CGPathRelease((CGPathRef) (p2.path)); +} + +// for a solid fill, we can merely have Core Graphics fill directly +static void fillSolid(CGContextRef ctxt, uiDrawPath *p, uiDrawBrush *b) +{ + // TODO this uses DeviceRGB; switch to sRGB + CGContextSetRGBFillColor(ctxt, b->R, b->G, b->B, b->A); + switch (p->fillMode) { + case uiDrawFillModeWinding: + CGContextFillPath(ctxt); + break; + case uiDrawFillModeAlternate: + CGContextEOFillPath(ctxt); + break; + } +} + +// for a gradient fill, we need to clip to the path and then draw the gradient +// see http://stackoverflow.com/a/25034854/3408572 +static void fillGradient(CGContextRef ctxt, uiDrawPath *p, uiDrawBrush *b) +{ + CGGradientRef gradient; + CGColorSpaceRef colorspace; + CGFloat *colors; + CGFloat *locations; + size_t i; + + // gradients need a color space + // for consistency with windows, use sRGB + colorspace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB); + if (colorspace == NULL) { + // TODO + } + // TODO add NULL check to other uses of CGColorSpace + + // make the gradient + colors = uiprivAlloc(b->NumStops * 4 * sizeof (CGFloat), "CGFloat[]"); + locations = uiprivAlloc(b->NumStops * sizeof (CGFloat), "CGFloat[]"); + for (i = 0; i < b->NumStops; i++) { + colors[i * 4 + 0] = b->Stops[i].R; + colors[i * 4 + 1] = b->Stops[i].G; + colors[i * 4 + 2] = b->Stops[i].B; + colors[i * 4 + 3] = b->Stops[i].A; + locations[i] = b->Stops[i].Pos; + } + gradient = CGGradientCreateWithColorComponents(colorspace, colors, locations, b->NumStops); + uiprivFree(locations); + uiprivFree(colors); + + // because we're mucking with clipping, we need to save the graphics state and restore it later + CGContextSaveGState(ctxt); + + // clip + switch (p->fillMode) { + case uiDrawFillModeWinding: + CGContextClip(ctxt); + break; + case uiDrawFillModeAlternate: + CGContextEOClip(ctxt); + break; + } + + // draw the gradient + switch (b->Type) { + case uiDrawBrushTypeLinearGradient: + CGContextDrawLinearGradient(ctxt, + gradient, + CGPointMake(b->X0, b->Y0), + CGPointMake(b->X1, b->Y1), + kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation); + break; + case uiDrawBrushTypeRadialGradient: + CGContextDrawRadialGradient(ctxt, + gradient, + CGPointMake(b->X0, b->Y0), + // make the start circle radius 0 to make it a point + 0, + CGPointMake(b->X1, b->Y1), + b->OuterRadius, + kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation); + break; + } + + // and clean up + CGContextRestoreGState(ctxt); + CGGradientRelease(gradient); + CGColorSpaceRelease(colorspace); +} + +void uiDrawFill(uiDrawContext *c, uiDrawPath *path, uiDrawBrush *b) +{ + if (!path->ended) + uiprivUserBug("You cannot call uiDrawStroke() on a uiDrawPath that has not been ended. (path: %p)", path); + CGContextAddPath(c->c, (CGPathRef) (path->path)); + switch (b->Type) { + case uiDrawBrushTypeSolid: + fillSolid(c->c, path, b); + return; + case uiDrawBrushTypeLinearGradient: + case uiDrawBrushTypeRadialGradient: + fillGradient(c->c, path, b); + return; +// case uiDrawBrushTypeImage: + // TODO + return; + } + uiprivUserBug("Unknown brush type %d passed to uiDrawFill().", b->Type); +} + +static void m2c(uiDrawMatrix *m, CGAffineTransform *c) +{ + c->a = m->M11; + c->b = m->M12; + c->c = m->M21; + c->d = m->M22; + c->tx = m->M31; + c->ty = m->M32; +} + +static void c2m(CGAffineTransform *c, uiDrawMatrix *m) +{ + m->M11 = c->a; + m->M12 = c->b; + m->M21 = c->c; + m->M22 = c->d; + m->M31 = c->tx; + m->M32 = c->ty; +} + +void uiDrawMatrixTranslate(uiDrawMatrix *m, double x, double y) +{ + CGAffineTransform c; + + m2c(m, &c); + c = CGAffineTransformTranslate(c, x, y); + c2m(&c, m); +} + +void uiDrawMatrixScale(uiDrawMatrix *m, double xCenter, double yCenter, double x, double y) +{ + CGAffineTransform c; + double xt, yt; + + m2c(m, &c); + xt = x; + yt = y; + uiprivScaleCenter(xCenter, yCenter, &xt, &yt); + c = CGAffineTransformTranslate(c, xt, yt); + c = CGAffineTransformScale(c, x, y); + c = CGAffineTransformTranslate(c, -xt, -yt); + c2m(&c, m); +} + +void uiDrawMatrixRotate(uiDrawMatrix *m, double x, double y, double amount) +{ + CGAffineTransform c; + + m2c(m, &c); + c = CGAffineTransformTranslate(c, x, y); + c = CGAffineTransformRotate(c, amount); + c = CGAffineTransformTranslate(c, -x, -y); + c2m(&c, m); +} + +void uiDrawMatrixSkew(uiDrawMatrix *m, double x, double y, double xamount, double yamount) +{ + uiprivFallbackSkew(m, x, y, xamount, yamount); +} + +void uiDrawMatrixMultiply(uiDrawMatrix *dest, uiDrawMatrix *src) +{ + CGAffineTransform c; + CGAffineTransform d; + + m2c(dest, &c); + m2c(src, &d); + c = CGAffineTransformConcat(c, d); + c2m(&c, dest); +} + +// there is no test for invertibility; CGAffineTransformInvert() is merely documented as returning the matrix unchanged if it isn't invertible +// therefore, special care must be taken to catch matrices who are their own inverses +// TODO figure out which matrices these are and do so +int uiDrawMatrixInvertible(uiDrawMatrix *m) +{ + CGAffineTransform c, d; + + m2c(m, &c); + d = CGAffineTransformInvert(c); + return CGAffineTransformEqualToTransform(c, d) == false; +} + +int uiDrawMatrixInvert(uiDrawMatrix *m) +{ + CGAffineTransform c, d; + + m2c(m, &c); + d = CGAffineTransformInvert(c); + if (CGAffineTransformEqualToTransform(c, d)) + return 0; + c2m(&d, m); + return 1; +} + +void uiDrawMatrixTransformPoint(uiDrawMatrix *m, double *x, double *y) +{ + CGAffineTransform c; + CGPoint p; + + m2c(m, &c); + p = CGPointApplyAffineTransform(CGPointMake(*x, *y), c); + *x = p.x; + *y = p.y; +} + +void uiDrawMatrixTransformSize(uiDrawMatrix *m, double *x, double *y) +{ + CGAffineTransform c; + CGSize s; + + m2c(m, &c); + s = CGSizeApplyAffineTransform(CGSizeMake(*x, *y), c); + *x = s.width; + *y = s.height; +} + +void uiDrawTransform(uiDrawContext *c, uiDrawMatrix *m) +{ + CGAffineTransform cm; + + m2c(m, &cm); + CGContextConcatCTM(c->c, cm); +} + +void uiDrawClip(uiDrawContext *c, uiDrawPath *path) +{ + if (!path->ended) + uiprivUserBug("You cannot call uiDrawCilp() on a uiDrawPath that has not been ended. (path: %p)", path); + CGContextAddPath(c->c, (CGPathRef) (path->path)); + switch (path->fillMode) { + case uiDrawFillModeWinding: + CGContextClip(c->c); + break; + case uiDrawFillModeAlternate: + CGContextEOClip(c->c); + break; + } +} + +// TODO figure out what besides transforms these save/restore on all platforms +void uiDrawSave(uiDrawContext *c) +{ + CGContextSaveGState(c->c); +} + +void uiDrawRestore(uiDrawContext *c) +{ + CGContextRestoreGState(c->c); +} diff --git a/dep/libui/darwin/drawtext.m b/dep/libui/darwin/drawtext.m new file mode 100644 index 0000000..c04b402 --- /dev/null +++ b/dep/libui/darwin/drawtext.m @@ -0,0 +1,214 @@ +// 7 march 2018 +#import "uipriv_darwin.h" +#import "draw.h" +#import "attrstr.h" + +// problem: for a CTFrame made from an empty string, the CTLine array will be empty, and we will crash when doing anything requiring a CTLine +// solution: for those cases, maintain a separate framesetter just for computing those things +// in the usual case, the separate copy will just be identical to the regular one, with extra references to everything within +@interface uiprivTextFrame : NSObject { + CFAttributedStringRef attrstr; + NSArray *backgroundParams; + CTFramesetterRef framesetter; + CGSize size; + CGPathRef path; + CTFrameRef frame; +} +- (id)initWithLayoutParams:(uiDrawTextLayoutParams *)p; +- (void)draw:(uiDrawContext *)c textLayout:(uiDrawTextLayout *)tl at:(double)x y:(double)y; +- (void)returnWidth:(double *)width height:(double *)height; +- (CFArrayRef)lines; +@end + +@implementation uiprivDrawTextBackgroundParams + +- (id)initWithStart:(size_t)s end:(size_t)e r:(double)red g:(double)green b:(double)blue a:(double)alpha +{ + self = [super init]; + if (self) { + self->start = s; + self->end = e; + self->r = red; + self->g = green; + self->b = blue; + self->a = alpha; + } + return self; +} + +- (void)draw:(CGContextRef)c layout:(uiDrawTextLayout *)layout at:(double)x y:(double)y utf8Mapping:(const size_t *)u16tou8 +{ + // TODO +} + +@end + +@implementation uiprivTextFrame + +- (id)initWithLayoutParams:(uiDrawTextLayoutParams *)p +{ + CFRange range; + CGFloat cgwidth; + CFRange unused; + CGRect rect; + + self = [super init]; + if (self) { + self->attrstr = uiprivAttributedStringToCFAttributedString(p, &(self->backgroundParams)); + // TODO kCTParagraphStyleSpecifierMaximumLineSpacing, kCTParagraphStyleSpecifierMinimumLineSpacing, kCTParagraphStyleSpecifierLineSpacingAdjustment for line spacing + self->framesetter = CTFramesetterCreateWithAttributedString(self->attrstr); + if (self->framesetter == NULL) { + // TODO + } + + range.location = 0; + range.length = CFAttributedStringGetLength(self->attrstr); + + cgwidth = (CGFloat) (p->Width); + if (cgwidth < 0) + cgwidth = CGFLOAT_MAX; + self->size = CTFramesetterSuggestFrameSizeWithConstraints(self->framesetter, + range, + // TODO kCTFramePathWidthAttributeName? + NULL, + CGSizeMake(cgwidth, CGFLOAT_MAX), + &unused); // not documented as accepting NULL (TODO really?) + + rect.origin = CGPointZero; + rect.size = self->size; + self->path = CGPathCreateWithRect(rect, NULL); + self->frame = CTFramesetterCreateFrame(self->framesetter, + range, + self->path, + // TODO kCTFramePathWidthAttributeName? + NULL); + if (self->frame == NULL) { + // TODO + } + } + return self; +} + +- (void)dealloc +{ + CFRelease(self->frame); + CFRelease(self->path); + CFRelease(self->framesetter); + [self->backgroundParams release]; + CFRelease(self->attrstr); + [super dealloc]; +} + +- (void)draw:(uiDrawContext *)c textLayout:(uiDrawTextLayout *)tl at:(double)x y:(double)y +{ + uiprivDrawTextBackgroundParams *dtb; + CGAffineTransform textMatrix; + + CGContextSaveGState(c->c); + // save the text matrix because it's not part of the graphics state + textMatrix = CGContextGetTextMatrix(c->c); + + for (dtb in self->backgroundParams) + /* TODO */; + + // Core Text doesn't draw onto a flipped view correctly; we have to pretend it was unflipped + // see the iOS bits of the first example at https://developer.apple.com/library/mac/documentation/StringsTextFonts/Conceptual/CoreText_Programming/LayoutOperations/LayoutOperations.html#//apple_ref/doc/uid/TP40005533-CH12-SW1 (iOS is naturally flipped) + // TODO how is this affected by a non-identity CTM? + CGContextTranslateCTM(c->c, 0, c->height); + CGContextScaleCTM(c->c, 1.0, -1.0); + CGContextSetTextMatrix(c->c, CGAffineTransformIdentity); + + // wait, that's not enough; we need to offset y values to account for our new flipping + // TODO explain this calculation + y = c->height - self->size.height - y; + + // CTFrameDraw() draws in the path we specified when creating the frame + // this means that in our usage, CTFrameDraw() will draw at (0,0) + // so move the origin to be at (x,y) instead + // TODO are the signs correct? + CGContextTranslateCTM(c->c, x, y); + + CTFrameDraw(self->frame, c->c); + + CGContextSetTextMatrix(c->c, textMatrix); + CGContextRestoreGState(c->c); +} + +- (void)returnWidth:(double *)width height:(double *)height +{ + if (width != NULL) + *width = self->size.width; + if (height != NULL) + *height = self->size.height; +} + +- (CFArrayRef)lines +{ + return CTFrameGetLines(self->frame); +} + +@end + +struct uiDrawTextLayout { + uiprivTextFrame *frame; + uiprivTextFrame *forLines; + BOOL empty; + + // for converting CFAttributedString indices from/to byte offsets + size_t *u8tou16; + size_t nUTF8; + size_t *u16tou8; + size_t nUTF16; +}; + +uiDrawTextLayout *uiDrawNewTextLayout(uiDrawTextLayoutParams *p) +{ + uiDrawTextLayout *tl; + + tl = uiprivNew(uiDrawTextLayout); + tl->frame = [[uiprivTextFrame alloc] initWithLayoutParams:p]; + if (uiAttributedStringLen(p->String) != 0) + tl->forLines = [tl->frame retain]; + else { + uiAttributedString *space; + uiDrawTextLayoutParams p2; + + tl->empty = YES; + space = uiNewAttributedString(" "); + p2 = *p; + p2.String = space; + tl->forLines = [[uiprivTextFrame alloc] initWithLayoutParams:&p2]; + uiFreeAttributedString(space); + } + + // and finally copy the UTF-8/UTF-16 conversion tables + tl->u8tou16 = uiprivAttributedStringCopyUTF8ToUTF16Table(p->String, &(tl->nUTF8)); + tl->u16tou8 = uiprivAttributedStringCopyUTF16ToUTF8Table(p->String, &(tl->nUTF16)); + return tl; +} + +void uiDrawFreeTextLayout(uiDrawTextLayout *tl) +{ + uiprivFree(tl->u16tou8); + uiprivFree(tl->u8tou16); + [tl->forLines release]; + [tl->frame release]; + uiprivFree(tl); +} + +// TODO document that (x,y) is the top-left corner of the *entire frame* +void uiDrawText(uiDrawContext *c, uiDrawTextLayout *tl, double x, double y) +{ + [tl->frame draw:c textLayout:tl at:x y:y]; +} + +// TODO document that the width and height of a layout is not necessarily the sum of the widths and heights of its constituent lines +// TODO width doesn't include trailing whitespace... +// TODO figure out how paragraph spacing should play into this +// TODO standardize and document the behavior of this on an empty layout +void uiDrawTextLayoutExtents(uiDrawTextLayout *tl, double *width, double *height) +{ + // TODO explain this, given the above + [tl->frame returnWidth:width height:NULL]; + [tl->forLines returnWidth:NULL height:height]; +} diff --git a/dep/libui/darwin/editablecombo.m b/dep/libui/darwin/editablecombo.m new file mode 100644 index 0000000..7b1a113 --- /dev/null +++ b/dep/libui/darwin/editablecombo.m @@ -0,0 +1,186 @@ +// 14 august 2015 +#import "uipriv_darwin.h" + +// So why did I split uiCombobox into uiCombobox and uiEditableCombobox? Here's (90% of the; the other 10% is GTK+ events) answer: +// When you type a value into a NSComboBox that just happens to be in the list, it will autoselect that item! +// I can't seem to find a workaround. +// Fortunately, there's other weird behaviors that made this split worth it. +// And besides, selected items make little sense with editable comboboxes... you either separate or combine them with the text entry :V + +// NSComboBoxes have no intrinsic width; we'll use the default Interface Builder width for them. +#define comboboxWidth 96 + +@interface libui_intrinsicWidthNSComboBox : NSComboBox +@end + +@implementation libui_intrinsicWidthNSComboBox + +- (NSSize)intrinsicContentSize +{ + NSSize s; + + s = [super intrinsicContentSize]; + s.width = comboboxWidth; + return s; +} + +@end + +struct uiEditableCombobox { + uiDarwinControl c; + NSComboBox *cb; + void (*onChanged)(uiEditableCombobox *, void *); + void *onChangedData; +}; + +@interface editableComboboxDelegateClass : NSObject { + uiprivMap *comboboxes; +} +- (void)controlTextDidChange:(NSNotification *)note; +- (void)comboBoxSelectionDidChange:(NSNotification *)note; +- (void)registerCombobox:(uiEditableCombobox *)c; +- (void)unregisterCombobox:(uiEditableCombobox *)c; +@end + +@implementation editableComboboxDelegateClass + +- (id)init +{ + self = [super init]; + if (self) + self->comboboxes = uiprivNewMap(); + return self; +} + +- (void)dealloc +{ + uiprivMapDestroy(self->comboboxes); + [super dealloc]; +} + +- (void)controlTextDidChange:(NSNotification *)note +{ + uiEditableCombobox *c; + + // TODO normalize the cast styles in these calls + c = uiEditableCombobox(uiprivMapGet(self->comboboxes, [note object])); + (*(c->onChanged))(c, c->onChangedData); +} + +// the above doesn't handle when an item is selected; this will +- (void)comboBoxSelectionDidChange:(NSNotification *)note +{ + // except this is sent BEFORE the entry is changed, and that doesn't send the above, so + // this is via http://stackoverflow.com/a/21059819/3408572 - it avoids the need to manage selected items + // this still isn't perfect — I get residual changes to the same value while navigating the list — but it's good enough + [self performSelector:@selector(controlTextDidChange:) + withObject:note + afterDelay:0]; +} + +- (void)registerCombobox:(uiEditableCombobox *)c +{ + uiprivMapSet(self->comboboxes, c->cb, c); + [c->cb setDelegate:self]; +} + +- (void)unregisterCombobox:(uiEditableCombobox *)c +{ + [c->cb setDelegate:nil]; + uiprivMapDelete(self->comboboxes, c->cb); +} + +@end + +static editableComboboxDelegateClass *comboboxDelegate = nil; + +uiDarwinControlAllDefaultsExceptDestroy(uiEditableCombobox, cb) + +static void uiEditableComboboxDestroy(uiControl *cc) +{ + uiEditableCombobox *c = uiEditableCombobox(cc); + + [comboboxDelegate unregisterCombobox:c]; + [c->cb release]; + uiFreeControl(uiControl(c)); +} + +void uiEditableComboboxAppend(uiEditableCombobox *c, const char *text) +{ + [c->cb addItemWithObjectValue:uiprivToNSString(text)]; +} + +char *uiEditableComboboxText(uiEditableCombobox *c) +{ + return uiDarwinNSStringToText([c->cb stringValue]); +} + +void uiEditableComboboxSetText(uiEditableCombobox *c, const char *text) +{ + NSString *t; + + t = uiprivToNSString(text); + [c->cb setStringValue:t]; + // yes, let's imitate the behavior that caused uiEditableCombobox to be separate in the first place! + // just to avoid confusion when users see an option in the list in the text field but not selected in the list + [c->cb selectItemWithObjectValue:t]; +} + +#if 0 +// LONGTERM +void uiEditableComboboxSetSelected(uiEditableCombobox *c, int n) +{ + if (c->editable) { + // see https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ComboBox/Tasks/SettingComboBoxValue.html#//apple_ref/doc/uid/20000256 + id delegate; + + // this triggers the delegate; turn it off for now + delegate = [c->cb delegate]; + [c->cb setDelegate:nil]; + + // this seems to work fine for -1 too + [c->cb selectItemAtIndex:n]; + if (n == -1) + [c->cb setObjectValue:@""]; + else + [c->cb setObjectValue:[c->cb objectValueOfSelectedItem]]; + + [c->cb setDelegate:delegate]; + return; + } + [c->pb selectItemAtIndex:n]; +} +#endif + +void uiEditableComboboxOnChanged(uiEditableCombobox *c, void (*f)(uiEditableCombobox *c, void *data), void *data) +{ + c->onChanged = f; + c->onChangedData = data; +} + +static void defaultOnChanged(uiEditableCombobox *c, void *data) +{ + // do nothing +} + +uiEditableCombobox *uiNewEditableCombobox(void) +{ + uiEditableCombobox *c; + + uiDarwinNewControl(uiEditableCombobox, c); + + c->cb = [[libui_intrinsicWidthNSComboBox alloc] initWithFrame:NSZeroRect]; + [c->cb setUsesDataSource:NO]; + [c->cb setButtonBordered:YES]; + [c->cb setCompletes:NO]; + uiDarwinSetControlFont(c->cb, NSRegularControlSize); + + if (comboboxDelegate == nil) { + comboboxDelegate = [[editableComboboxDelegateClass new] autorelease]; + [uiprivDelegates addObject:comboboxDelegate]; + } + [comboboxDelegate registerCombobox:c]; + uiEditableComboboxOnChanged(c, defaultOnChanged, NULL); + + return c; +} diff --git a/dep/libui/darwin/entry.m b/dep/libui/darwin/entry.m new file mode 100644 index 0000000..9963026 --- /dev/null +++ b/dep/libui/darwin/entry.m @@ -0,0 +1,251 @@ +// 14 august 2015 +#import "uipriv_darwin.h" + +// Text fields for entering text have no intrinsic width; we'll use the default Interface Builder width for them. +#define textfieldWidth 96 + +@interface libui_intrinsicWidthNSTextField : NSTextField +@end + +@implementation libui_intrinsicWidthNSTextField + +- (NSSize)intrinsicContentSize +{ + NSSize s; + + s = [super intrinsicContentSize]; + s.width = textfieldWidth; + return s; +} + +@end + +// TODO does this have one on its own? +@interface libui_intrinsicWidthNSSecureTextField : NSSecureTextField +@end + +@implementation libui_intrinsicWidthNSSecureTextField + +- (NSSize)intrinsicContentSize +{ + NSSize s; + + s = [super intrinsicContentSize]; + s.width = textfieldWidth; + return s; +} + +@end + +// TODO does this have one on its own? +@interface libui_intrinsicWidthNSSearchField : NSSearchField +@end + +@implementation libui_intrinsicWidthNSSearchField + +- (NSSize)intrinsicContentSize +{ + NSSize s; + + s = [super intrinsicContentSize]; + s.width = textfieldWidth; + return s; +} + +@end + +struct uiEntry { + uiDarwinControl c; + NSTextField *textfield; + void (*onChanged)(uiEntry *, void *); + void *onChangedData; +}; + +static BOOL isSearchField(NSTextField *tf) +{ + return [tf isKindOfClass:[NSSearchField class]]; +} + +@interface entryDelegateClass : NSObject { + uiprivMap *entries; +} +- (void)controlTextDidChange:(NSNotification *)note; +- (IBAction)onSearch:(id)sender; +- (void)registerEntry:(uiEntry *)e; +- (void)unregisterEntry:(uiEntry *)e; +@end + +@implementation entryDelegateClass + +- (id)init +{ + self = [super init]; + if (self) + self->entries = uiprivNewMap(); + return self; +} + +- (void)dealloc +{ + uiprivMapDestroy(self->entries); + [super dealloc]; +} + +- (void)controlTextDidChange:(NSNotification *)note +{ + [self onSearch:[note object]]; +} + +- (IBAction)onSearch:(id)sender +{ + uiEntry *e; + + e = (uiEntry *) uiprivMapGet(self->entries, sender); + (*(e->onChanged))(e, e->onChangedData); +} + +- (void)registerEntry:(uiEntry *)e +{ + uiprivMapSet(self->entries, e->textfield, e); + if (isSearchField(e->textfield)) { + [e->textfield setTarget:self]; + [e->textfield setAction:@selector(onSearch:)]; + } else + [e->textfield setDelegate:self]; +} + +- (void)unregisterEntry:(uiEntry *)e +{ + if (isSearchField(e->textfield)) + [e->textfield setTarget:nil]; + else + [e->textfield setDelegate:nil]; + uiprivMapDelete(self->entries, e->textfield); +} + +@end + +static entryDelegateClass *entryDelegate = nil; + +uiDarwinControlAllDefaultsExceptDestroy(uiEntry, textfield) + +static void uiEntryDestroy(uiControl *c) +{ + uiEntry *e = uiEntry(c); + + [entryDelegate unregisterEntry:e]; + [e->textfield release]; + uiFreeControl(uiControl(e)); +} + +char *uiEntryText(uiEntry *e) +{ + return uiDarwinNSStringToText([e->textfield stringValue]); +} + +void uiEntrySetText(uiEntry *e, const char *text) +{ + [e->textfield setStringValue:uiprivToNSString(text)]; + // don't queue the control for resize; entry sizes are independent of their contents +} + +void uiEntryOnChanged(uiEntry *e, void (*f)(uiEntry *, void *), void *data) +{ + e->onChanged = f; + e->onChangedData = data; +} + +int uiEntryReadOnly(uiEntry *e) +{ + return [e->textfield isEditable] == NO; +} + +void uiEntrySetReadOnly(uiEntry *e, int readonly) +{ + BOOL editable; + + editable = YES; + if (readonly) + editable = NO; + [e->textfield setEditable:editable]; +} + +static void defaultOnChanged(uiEntry *e, void *data) +{ + // do nothing +} + +// these are based on interface builder defaults; my comments in the old code weren't very good so I don't really know what talked about what, sorry :/ +void uiprivFinishNewTextField(NSTextField *t, BOOL isEntry) +{ + uiDarwinSetControlFont(t, NSRegularControlSize); + + // THE ORDER OF THESE CALLS IS IMPORTANT; CHANGE IT AND THE BORDERS WILL DISAPPEAR + [t setBordered:NO]; + [t setBezelStyle:NSTextFieldSquareBezel]; + [t setBezeled:isEntry]; + + // we don't need to worry about substitutions/autocorrect here; see window_darwin.m for details + + [[t cell] setLineBreakMode:NSLineBreakByClipping]; + [[t cell] setScrollable:YES]; +} + +static NSTextField *realNewEditableTextField(Class class) +{ + NSTextField *tf; + + tf = [[class alloc] initWithFrame:NSZeroRect]; + [tf setSelectable:YES]; // otherwise the setting is masked by the editable default of YES + uiprivFinishNewTextField(tf, YES); + return tf; +} + +NSTextField *uiprivNewEditableTextField(void) +{ + return realNewEditableTextField([libui_intrinsicWidthNSTextField class]); +} + +static uiEntry *finishNewEntry(Class class) +{ + uiEntry *e; + + uiDarwinNewControl(uiEntry, e); + + e->textfield = realNewEditableTextField(class); + + if (entryDelegate == nil) { + entryDelegate = [[entryDelegateClass new] autorelease]; + [uiprivDelegates addObject:entryDelegate]; + } + [entryDelegate registerEntry:e]; + uiEntryOnChanged(e, defaultOnChanged, NULL); + + return e; +} + +uiEntry *uiNewEntry(void) +{ + return finishNewEntry([libui_intrinsicWidthNSTextField class]); +} + +uiEntry *uiNewPasswordEntry(void) +{ + return finishNewEntry([libui_intrinsicWidthNSSecureTextField class]); +} + +uiEntry *uiNewSearchEntry(void) +{ + uiEntry *e; + NSSearchField *s; + + e = finishNewEntry([libui_intrinsicWidthNSSearchField class]); + s = (NSSearchField *) (e->textfield); + // TODO these are only on 10.10 +// [s setSendsSearchStringImmediately:NO]; +// [s setSendsWholeSearchString:NO]; + [s setBordered:NO]; + [s setBezelStyle:NSTextFieldRoundedBezel]; + [s setBezeled:YES]; + return e; +} diff --git a/dep/libui/darwin/fontbutton.m b/dep/libui/darwin/fontbutton.m new file mode 100644 index 0000000..0ef57d8 --- /dev/null +++ b/dep/libui/darwin/fontbutton.m @@ -0,0 +1,232 @@ +// 14 april 2016 +#import "uipriv_darwin.h" +#import "attrstr.h" + +@interface uiprivFontButton : NSButton { + uiFontButton *libui_b; + NSFont *libui_font; +} +- (id)initWithFrame:(NSRect)frame libuiFontButton:(uiFontButton *)b; +- (void)updateFontButtonLabel; +- (IBAction)fontButtonClicked:(id)sender; +- (void)activateFontButton; +- (void)deactivateFontButton:(BOOL)activatingAnother; +- (void)deactivateOnClose:(NSNotification *)note; +- (void)getfontdesc:(uiFontDescriptor *)uidesc; +@end + +// only one may be active at one time +static uiprivFontButton *activeFontButton = nil; + +struct uiFontButton { + uiDarwinControl c; + uiprivFontButton *button; + void (*onChanged)(uiFontButton *, void *); + void *onChangedData; +}; + +@implementation uiprivFontButton + +- (id)initWithFrame:(NSRect)frame libuiFontButton:(uiFontButton *)b +{ + self = [super initWithFrame:frame]; + if (self) { + self->libui_b = b; + + // imitate a NSColorWell in appearance + [self setButtonType:NSPushOnPushOffButton]; + [self setBordered:YES]; + [self setBezelStyle:NSShadowlessSquareBezelStyle]; + + // default font values according to the CTFontDescriptor reference + // this is autoreleased (thanks swillits in irc.freenode.net/#macdev) + self->libui_font = [[NSFont fontWithName:@"Helvetica" size:12.0] retain]; + [self updateFontButtonLabel]; + + // for when clicked + [self setTarget:self]; + [self setAction:@selector(fontButtonClicked:)]; + } + return self; +} + +- (void)dealloc +{ + // clean up notifications + if (activeFontButton == self) + [self deactivateFontButton:NO]; + [self->libui_font release]; + [super dealloc]; +} + +- (void)updateFontButtonLabel +{ + NSString *title; + + title = [NSString stringWithFormat:@"%@ %g", + [self->libui_font displayName], + [self->libui_font pointSize]]; + [self setTitle:title]; +} + +- (IBAction)fontButtonClicked:(id)sender +{ + if ([self state] == NSOnState) + [self activateFontButton]; + else + [self deactivateFontButton:NO]; +} + +- (void)activateFontButton +{ + NSFontManager *sfm; + + sfm = [NSFontManager sharedFontManager]; + if (activeFontButton != nil) + [activeFontButton deactivateFontButton:YES]; + [sfm setTarget:self]; + [sfm setSelectedFont:self->libui_font isMultiple:NO]; + [sfm orderFrontFontPanel:self]; + activeFontButton = self; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(deactivateOnClose:) + name:NSWindowWillCloseNotification + object:[NSFontPanel sharedFontPanel]]; + [self setState:NSOnState]; +} + +- (void)deactivateFontButton:(BOOL)activatingAnother +{ + NSFontManager *sfm; + + sfm = [NSFontManager sharedFontManager]; + [sfm setTarget:nil]; + if (!activatingAnother) + [[NSFontPanel sharedFontPanel] orderOut:self]; + activeFontButton = nil; + [[NSNotificationCenter defaultCenter] removeObserver:self + name:NSWindowWillCloseNotification + object:[NSFontPanel sharedFontPanel]]; + [self setState:NSOffState]; +} + +- (void)deactivateOnClose:(NSNotification *)note +{ + [self deactivateFontButton:NO]; +} + +- (void)changeFont:(id)sender +{ + NSFontManager *fm; + NSFont *old; + uiFontButton *b = self->libui_b; + + fm = (NSFontManager *) sender; + old = self->libui_font; + self->libui_font = [sender convertFont:self->libui_font]; + // do this even if it returns the same; we don't own anything that isn't from a new or alloc/init + [self->libui_font retain]; + // do this second just in case + [old release]; + [self updateFontButtonLabel]; + (*(b->onChanged))(b, b->onChangedData); +} + +- (NSUInteger)validModesForFontPanel:(NSFontPanel *)panel +{ + return NSFontPanelFaceModeMask | + NSFontPanelSizeModeMask | + NSFontPanelCollectionModeMask; +} + +- (void)getfontdesc:(uiFontDescriptor *)uidesc +{ + CTFontRef ctfont; + CTFontDescriptorRef ctdesc; + + ctfont = (CTFontRef) (self->libui_font); + ctdesc = CTFontCopyFontDescriptor(ctfont); + uiprivFontDescriptorFromCTFontDescriptor(ctdesc, uidesc); + CFRelease(ctdesc); + uidesc->Size = CTFontGetSize(ctfont); +} + +@end + +uiDarwinControlAllDefaults(uiFontButton, button) + +// we do not want font change events to be sent to any controls other than the font buttons +// see main.m for more details +BOOL uiprivFontButtonInhibitSendAction(SEL sel, id from, id to) +{ + if (sel != @selector(changeFont:)) + return NO; + return ![to isKindOfClass:[uiprivFontButton class]]; +} + +// we do not want NSFontPanelValidation messages to be sent to any controls other than the font buttons when a font button is active +// see main.m for more details +BOOL uiprivFontButtonOverrideTargetForAction(SEL sel, id from, id to, id *override) +{ + if (activeFontButton == nil) + return NO; + if (sel != @selector(validModesForFontPanel:)) + return NO; + *override = activeFontButton; + return YES; +} + +// we also don't want the panel to be usable when there's a dialog running; see stddialogs.m for more details on that +// unfortunately the panel seems to ignore -setWorksWhenModal: so we'll have to do things ourselves +@interface uiprivNonModalFontPanel : NSFontPanel +@end + +@implementation uiprivNonModalFontPanel + +- (BOOL)worksWhenModal +{ + return NO; +} + +@end + +void uiprivSetupFontPanel(void) +{ + [NSFontManager setFontPanelFactory:[uiprivNonModalFontPanel class]]; +} + +static void defaultOnChanged(uiFontButton *b, void *data) +{ + // do nothing +} + +void uiFontButtonFont(uiFontButton *b, uiFontDescriptor *desc) +{ + [b->button getfontdesc:desc]; +} + +void uiFontButtonOnChanged(uiFontButton *b, void (*f)(uiFontButton *, void *), void *data) +{ + b->onChanged = f; + b->onChangedData = data; +} + +uiFontButton *uiNewFontButton(void) +{ + uiFontButton *b; + + uiDarwinNewControl(uiFontButton, b); + + b->button = [[uiprivFontButton alloc] initWithFrame:NSZeroRect libuiFontButton:b]; + uiDarwinSetControlFont(b->button, NSRegularControlSize); + + uiFontButtonOnChanged(b, defaultOnChanged, NULL); + + return b; +} + +void uiFreeFontButtonFont(uiFontDescriptor *desc) +{ + // TODO ensure this is synchronized with fontmatch.m + uiFreeText((char *) (desc->Family)); +} diff --git a/dep/libui/darwin/fontmatch.m b/dep/libui/darwin/fontmatch.m new file mode 100644 index 0000000..6daa1e8 --- /dev/null +++ b/dep/libui/darwin/fontmatch.m @@ -0,0 +1,494 @@ +// 3 january 2017 +#import "uipriv_darwin.h" +#import "attrstr.h" + +// TODOs: +// - switching from Skia to a non-fvar-based font crashes because the CTFontDescriptorRef we get has an empty variation dictionary for some reason... +// - Futura causes the Courier New in the drawtext example to be bold for some reason... + +// Core Text exposes font style info in two forms: +// - Fonts with a QuickDraw GX font variation (fvar) table, a feature +// adopted by OpenType, expose variations directly. +// - All other fonts have Core Text normalize the font style info +// into a traits dictionary. +// Of course this setup doesn't come without its hiccups and +// glitches. In particular, not only are the exact rules not well +// defined, but also font matching doesn't work as we want it to +// (exactly how varies based on the way the style info is exposed). +// So we'll have to implement style matching ourselves. +// We can use Core Text's matching to get a complete list of +// *possible* matches, and then we can filter out the ones we don't +// want ourselves. +// +// To make things easier for us, we'll match by converting Core +// Text's values back into libui values. This allows us to also use the +// normalization code for filling in uiFontDescriptors from +// Core Text fonts and font descriptors. +// +// Style matching needs to be done early in the font loading process; +// in particular, we have to do this before adding any features, +// because the descriptors returned by Core Text's own font +// matching won't have any. + +@implementation uiprivFontStyleData + +- (id)initWithFont:(CTFontRef)f +{ + self = [super init]; + if (self) { + self->font = f; + CFRetain(self->font); + self->desc = CTFontCopyFontDescriptor(self->font); + if (![self prepare]) { + [self release]; + return nil; + } + } + return self; +} + +- (id)initWithDescriptor:(CTFontDescriptorRef)d +{ + self = [super init]; + if (self) { + self->font = NULL; + self->desc = d; + CFRetain(self->desc); + if (![self prepare]) { + [self release]; + return nil; + } + } + return self; +} + +- (void)dealloc +{ +#define REL(x) if (x != NULL) { CFRelease(x); x = NULL; } + REL(self->variationAxes); + REL(self->familyName); + REL(self->preferredFamilyName); + REL(self->fullName); + REL(self->subFamilyName); + REL(self->preferredSubFamilyName); + REL(self->postScriptName); + REL(self->variation); + REL(self->styleName); + REL(self->traits); + CFRelease(self->desc); + REL(self->font); + [super dealloc]; +} + +- (BOOL)prepare +{ + CFNumberRef num; + Boolean success; + + self->traits = NULL; + self->symbolic = 0; + self->weight = 0; + self->width = 0; + self->didStyleName = NO; + self->styleName = NULL; + self->didVariation = NO; + self->variation = NULL; + self->hasRegistrationScope = NO; + self->registrationScope = 0; + self->didPostScriptName = NO; + self->postScriptName = NULL; + self->fontFormat = 0; + self->didPreferredSubFamilyName = NO; + self->preferredSubFamilyName = NULL; + self->didSubFamilyName = NO; + self->subFamilyName = NULL; + self->didFullName = NO; + self->fullName = NULL; + self->didPreferredFamilyName = NO; + self->preferredFamilyName = NULL; + self->didFamilyName = NO; + self->familyName = NULL; + self->didVariationAxes = NO; + self->variationAxes = NULL; + + self->traits = (CFDictionaryRef) CTFontDescriptorCopyAttribute(self->desc, kCTFontTraitsAttribute); + if (self->traits == NULL) + return NO; + + num = (CFNumberRef) CFDictionaryGetValue(self->traits, kCTFontSymbolicTrait); + if (num == NULL) + return NO; + if (CFNumberGetValue(num, kCFNumberSInt32Type, &(self->symbolic)) == false) + return NO; + + num = (CFNumberRef) CFDictionaryGetValue(self->traits, kCTFontWeightTrait); + if (num == NULL) + return NO; + if (CFNumberGetValue(num, kCFNumberDoubleType, &(self->weight)) == false) + return NO; + + num = (CFNumberRef) CFDictionaryGetValue(self->traits, kCTFontWidthTrait); + if (num == NULL) + return NO; + if (CFNumberGetValue(num, kCFNumberDoubleType, &(self->width)) == false) + return NO; + + // do these now for the sake of error checking + num = (CFNumberRef) CTFontDescriptorCopyAttribute(desc, kCTFontRegistrationScopeAttribute); + self->hasRegistrationScope = num != NULL; + if (self->hasRegistrationScope) { + success = CFNumberGetValue(num, kCFNumberSInt32Type, &(self->registrationScope)); + CFRelease(num); + if (success == false) + return NO; + } + + num = (CFNumberRef) CTFontDescriptorCopyAttribute(self->desc, kCTFontFormatAttribute); + if (num == NULL) + return NO; + success = CFNumberGetValue(num, kCFNumberSInt32Type, &(self->fontFormat)); + CFRelease(num); + if (success == false) + return NO; + + return YES; +} + +- (void)ensureFont +{ + if (self->font != NULL) + return; + self->font = CTFontCreateWithFontDescriptor(self->desc, 0.0, NULL); +} + +- (CTFontSymbolicTraits)symbolicTraits +{ + return self->symbolic; +} + +- (double)weight +{ + return self->weight; +} + +- (double)width +{ + return self->width; +} + +- (CFStringRef)styleName +{ + if (!self->didStyleName) { + self->didStyleName = YES; + self->styleName = (CFStringRef) CTFontDescriptorCopyAttribute(self->desc, kCTFontStyleNameAttribute); + // The code we use this for (guessItalicOblique() below) checks if this is NULL or not, so we're good. + } + return self->styleName; +} + +- (CFDictionaryRef)variation +{ + if (!self->didVariation) { + self->didVariation = YES; + self->variation = (CFDictionaryRef) CTFontDescriptorCopyAttribute(self->desc, kCTFontVariationAttribute); + // This being NULL is used to determine whether a font uses variations at all, so we don't need to worry now. + } + return self->variation; +} + +- (BOOL)hasRegistrationScope +{ + return self->hasRegistrationScope; +} + +- (CTFontManagerScope)registrationScope +{ + return self->registrationScope; +} + +- (CFStringRef)postScriptName +{ + if (!self->didPostScriptName) { + self->didPostScriptName = YES; + [self ensureFont]; + self->postScriptName = CTFontCopyPostScriptName(self->font); + } + return self->postScriptName; +} + +- (CFDataRef)table:(CTFontTableTag)tag +{ + [self ensureFont]; + return CTFontCopyTable(self->font, tag, kCTFontTableOptionNoOptions); +} + +- (CTFontFormat)fontFormat +{ + return self->fontFormat; +} + +// We don't need to worry if this or any of the functions that use it return NULL, because the code that uses it (libFontRegistry.dylib bug workarounds in fonttraits.m) checks for NULL. +- (CFStringRef)fontName:(CFStringRef)key +{ + [self ensureFont]; + return CTFontCopyName(self->font, key); +} + +#define FONTNAME(sel, did, var, key) \ + - (CFStringRef)sel \ + { \ + if (!did) { \ + did = YES; \ + var = [self fontName:key]; \ + } \ + return var; \ + } +FONTNAME(preferredSubFamilyName, + self->didPreferredSubFamilyName, + self->preferredSubFamilyName, + uiprivUNDOC_kCTFontPreferredSubFamilyNameKey) +FONTNAME(subFamilyName, + self->didSubFamilyName, + self->subFamilyName, + kCTFontSubFamilyNameKey) +FONTNAME(fullName, + self->didFullName, + self->fullName, + kCTFontFullNameKey) +FONTNAME(preferredFamilyName, + self->didPreferredFamilyName, + self->preferredFamilyName, + uiprivUNDOC_kCTFontPreferredFamilyNameKey) +FONTNAME(familyName, + self->didFamilyName, + self->familyName, + kCTFontFamilyNameKey) + +- (CFArrayRef)variationAxes +{ + if (!self->didVariationAxes) { + self->didVariationAxes = YES; + [self ensureFont]; + self->variationAxes = CTFontCopyVariationAxes(self->font); + // We don't care about the return value because we call this only on fonts that we know have variations anyway. + } + return self->variationAxes; +} + +@end + +struct closeness { + CFIndex index; + uiTextWeight weight; + double italic; + uiTextStretch stretch; + double distance; +}; + +// remember that in closeness, 0 means exact +// in this case, since we define the range, we use 0.5 to mean "close enough" (oblique for italic and italic for oblique) and 1 to mean "not a match" +static const double italicClosenessNormal[] = { 0, 1, 1 }; +static const double italicClosenessOblique[] = { 1, 0, 0.5 }; +static const double italicClosenessItalic[] = { 1, 0.5, 0 }; +static const double *italicClosenesses[] = { + [uiTextItalicNormal] = italicClosenessNormal, + [uiTextItalicOblique] = italicClosenessOblique, + [uiTextItalicItalic] = italicClosenessItalic, +}; + +// Core Text doesn't seem to differentiate between Italic and Oblique. +// Pango's Core Text code just does a g_strrstr() (backwards case-sensitive search) for "Oblique" in the font's style name (see https://git.gnome.org/browse/pango/tree/pango/pangocoretext-fontmap.c); let's do that too I guess +static uiTextItalic guessItalicOblique(uiprivFontStyleData *d) +{ + CFStringRef styleName; + BOOL isOblique; + + isOblique = NO; // default value + styleName = [d styleName]; + if (styleName != NULL) { + CFRange range; + + range = CFStringFind(styleName, CFSTR("Oblique"), kCFCompareBackwards); + if (range.location != kCFNotFound) + isOblique = YES; + } + if (isOblique) + return uiTextItalicOblique; + return uiTextItalicItalic; +} + +// Italics are hard because Core Text does NOT distinguish between italic and oblique. +// All Core Text provides is a slant value and the italic bit of the symbolic traits mask. +// However, Core Text does seem to guarantee (from experimentation; see below) that the slant will be nonzero if and only if the italic bit is set, so we don't need to use the slant value. +// Core Text also seems to guarantee that if a font lists itself as Italic or Oblique by name (font subfamily name, font style name, whatever), it will also have that bit set, so testing this bit does cover all fonts that name themselves as Italic and Oblique. (Again, this is from the below experimentation.) +// TODO there is still one catch that might matter from a user's POV: the reverse is not true — the italic bit can be set even if the style of the font face/subfamily/style isn't named as Italic (for example, script typefaces like Adobe's Palace Script MT Std); I don't know what to do about this... I know how to start: find a script font that has an italic form (Adobe's Palace Script MT Std does not; only Regular and Semibold) +static void setItalic(uiprivFontStyleData *d, uiFontDescriptor *out) +{ + out->Italic = uiTextItalicNormal; + if (([d symbolicTraits] & kCTFontItalicTrait) != 0) + out->Italic = guessItalicOblique(d); +} + +static void fillDescStyleFields(uiprivFontStyleData *d, NSDictionary *axisDict, uiFontDescriptor *out) +{ + setItalic(d, out); + if (axisDict != nil) + uiprivProcessFontVariation(d, axisDict, out); + else + uiprivProcessFontTraits(d, out); +} + +static CTFontDescriptorRef matchStyle(CTFontDescriptorRef against, uiFontDescriptor *styles) +{ + CFArrayRef matching; + CFIndex i, n; + struct closeness *closeness; + CTFontDescriptorRef current; + CTFontDescriptorRef out; + uiprivFontStyleData *d; + NSDictionary *axisDict; + + matching = CTFontDescriptorCreateMatchingFontDescriptors(against, NULL); + if (matching == NULL) + // no matches; give the original back and hope for the best + return against; + n = CFArrayGetCount(matching); + if (n == 0) { + // likewise + CFRelease(matching); + return against; + } + + current = (CTFontDescriptorRef) CFArrayGetValueAtIndex(matching, 0); + d = [[uiprivFontStyleData alloc] initWithDescriptor:current]; + axisDict = nil; + if ([d variation] != NULL) + axisDict = uiprivMakeVariationAxisDict([d variationAxes], [d table:kCTFontTableAvar]); + + closeness = (struct closeness *) uiprivAlloc(n * sizeof (struct closeness), "struct closeness[]"); + for (i = 0; i < n; i++) { + uiFontDescriptor fields; + + closeness[i].index = i; + if (i != 0) { + current = (CTFontDescriptorRef) CFArrayGetValueAtIndex(matching, i); + d = [[uiprivFontStyleData alloc] initWithDescriptor:current]; + } + fillDescStyleFields(d, axisDict, &fields); + closeness[i].weight = fields.Weight - styles->Weight; + closeness[i].italic = italicClosenesses[styles->Italic][fields.Italic]; + closeness[i].stretch = fields.Stretch - styles->Stretch; + [d release]; + } + + // now figure out the 3-space difference between the three and sort by that + // TODO merge this loop with the previous loop? + for (i = 0; i < n; i++) { + double weight, italic, stretch; + + weight = (double) (closeness[i].weight); + weight *= weight; + italic = closeness[i].italic; + italic *= italic; + stretch = (double) (closeness[i].stretch); + stretch *= stretch; + closeness[i].distance = sqrt(weight + italic + stretch); + } + qsort_b(closeness, n, sizeof (struct closeness), ^(const void *aa, const void *bb) { + const struct closeness *a = (const struct closeness *) aa; + const struct closeness *b = (const struct closeness *) bb; + + // via http://www.gnu.org/software/libc/manual/html_node/Comparison-Functions.html#Comparison-Functions + // LONGTERM is this really the best way? isn't it the same as if (*a < *b) return -1; if (*a > *b) return 1; return 0; ? + return (a->distance > b->distance) - (a->distance < b->distance); + }); + // and the first element of the sorted array is what we want + out = CFArrayGetValueAtIndex(matching, closeness[0].index); + CFRetain(out); // get rule + + // release everything + if (axisDict != nil) + [axisDict release]; + uiprivFree(closeness); + CFRelease(matching); + // and release the original descriptor since we no longer need it + CFRelease(against); + + return out; +} + +CTFontDescriptorRef uiprivFontDescriptorToCTFontDescriptor(uiFontDescriptor *fd) +{ + CFMutableDictionaryRef attrs; + CFStringRef cffamily; + CFNumberRef cfsize; + CTFontDescriptorRef basedesc; + + attrs = CFDictionaryCreateMutable(NULL, 2, + // TODO are these correct? + &kCFCopyStringDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + if (attrs == NULL) { + // TODO + } + cffamily = CFStringCreateWithCString(NULL, fd->Family, kCFStringEncodingUTF8); + if (cffamily == NULL) { + // TODO + } + CFDictionaryAddValue(attrs, kCTFontFamilyNameAttribute, cffamily); + CFRelease(cffamily); + cfsize = CFNumberCreate(NULL, kCFNumberDoubleType, &(fd->Size)); + CFDictionaryAddValue(attrs, kCTFontSizeAttribute, cfsize); + CFRelease(cfsize); + + basedesc = CTFontDescriptorCreateWithAttributes(attrs); + CFRelease(attrs); // TODO correct? + return matchStyle(basedesc, fd); +} + +// fortunately features that aren't supported are simply ignored, so we can copy them all in +CTFontDescriptorRef uiprivCTFontDescriptorAppendFeatures(CTFontDescriptorRef desc, const uiOpenTypeFeatures *otf) +{ + CTFontDescriptorRef new; + CFArrayRef featuresArray; + CFDictionaryRef attrs; + const void *keys[1], *values[1]; + + featuresArray = uiprivOpenTypeFeaturesToCTFeatures(otf); + keys[0] = kCTFontFeatureSettingsAttribute; + values[0] = featuresArray; + attrs = CFDictionaryCreate(NULL, + keys, values, 1, + // TODO are these correct? + &kCFCopyStringDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + CFRelease(featuresArray); + new = CTFontDescriptorCreateCopyWithAttributes(desc, attrs); + CFRelease(attrs); + CFRelease(desc); + return new; +} + +void uiprivFontDescriptorFromCTFontDescriptor(CTFontDescriptorRef ctdesc, uiFontDescriptor *uidesc) +{ + CFStringRef cffamily; + uiprivFontStyleData *d; + NSDictionary *axisDict; + + cffamily = (CFStringRef) CTFontDescriptorCopyAttribute(ctdesc, kCTFontFamilyNameAttribute); + if (cffamily == NULL) { + // TODO + } + // TODO normalize this by adding a uiDarwinCFStringToText() + uidesc->Family = uiDarwinNSStringToText((NSString *) cffamily); + CFRelease(cffamily); + + d = [[uiprivFontStyleData alloc] initWithDescriptor:ctdesc]; + axisDict = nil; + if ([d variation] != NULL) + axisDict = uiprivMakeVariationAxisDict([d variationAxes], [d table:kCTFontTableAvar]); + fillDescStyleFields(d, axisDict, uidesc); + if (axisDict != nil) + [axisDict release]; + [d release]; +} diff --git a/dep/libui/darwin/fonttraits.m b/dep/libui/darwin/fonttraits.m new file mode 100644 index 0000000..a51492c --- /dev/null +++ b/dep/libui/darwin/fonttraits.m @@ -0,0 +1,223 @@ +// 1 november 2017 +#import "uipriv_darwin.h" +#import "attrstr.h" + +// This is the part of the font style matching and normalization code +// that handles fonts that use a traits dictionary. +// +// Matching stupidity: Core Text requires an **exact match for the +// entire traits dictionary**, otherwise it will **drop ALL the traits**. +// +// Normalization stupidity: Core Text uses its own scaled values for +// weight and width, but the values are different if the font is not +// registered and if said font is TrueType or OpenType. The values +// for all other cases do have some named constants starting with +// OS X 10.11, but even these aren't very consistent in practice. +// +// Of course, none of this is documented anywhere, so I had to do +// both trial-and-error AND reverse engineering to figure out what's +// what. We'll just convert Core Text's values into libui constants +// and use those for matching. + +static BOOL fontRegistered(uiprivFontStyleData *d) +{ + if (![d hasRegistrationScope]) + // header says this should be treated as the same as not registered + return NO; + // examination of Core Text shows this is accurate + return [d registrationScope] != kCTFontManagerScopeNone; +} + +// Core Text does (usWidthClass / 10) - 0.5 here. +// This roughly maps to our values with increments of 0.1, except for the fact 0 and 10 are allowed by Core Text, despite being banned by TrueType and OpenType themselves. +// We'll just treat them as identical to 1 and 9, respectively. +static const uiTextStretch os2WidthsToStretches[] = { + uiTextStretchUltraCondensed, + uiTextStretchUltraCondensed, + uiTextStretchExtraCondensed, + uiTextStretchCondensed, + uiTextStretchSemiCondensed, + uiTextStretchNormal, + uiTextStretchSemiExpanded, + uiTextStretchExpanded, + uiTextStretchExtraExpanded, + uiTextStretchUltraExpanded, + uiTextStretchUltraExpanded, +}; + +static const CFStringRef exceptions[] = { + CFSTR("LucidaGrande"), + CFSTR(".LucidaGrandeUI"), + CFSTR("STHeiti"), + CFSTR("STXihei"), + CFSTR("TimesNewRomanPSMT"), + NULL, +}; + +static void trySecondaryOS2Values(uiprivFontStyleData *d, uiFontDescriptor *out, BOOL *hasWeight, BOOL *hasWidth) +{ + CFDataRef os2; + uint16_t usWeightClass, usWidthClass; + CFStringRef psname; + const CFStringRef *ex; + + *hasWeight = NO; + *hasWidth = NO; + + // only applies to unregistered fonts + if (fontRegistered(d)) + return; + + os2 = [d table:kCTFontTableOS2]; + if (os2 == NULL) + // no OS2 table, so no secondary values + return; + + if (CFDataGetLength(os2) > 77) { + const UInt8 *b; + + b = CFDataGetBytePtr(os2); + + usWeightClass = ((uint16_t) (b[4])) << 8; + usWeightClass |= (uint16_t) (b[5]); + if (usWeightClass <= 1000) { + if (usWeightClass < 11) + usWeightClass *= 100; + *hasWeight = YES; + } + + usWidthClass = ((uint16_t) (b[6])) << 8; + usWidthClass |= (uint16_t) (b[7]); + if (usWidthClass <= 10) + *hasWidth = YES; + } else { + usWeightClass = 0; + *hasWeight = YES; + + usWidthClass = 0; + *hasWidth = YES; + } + if (*hasWeight) + // we can just use this directly + out->Weight = usWeightClass; + if (*hasWidth) + out->Stretch = os2WidthsToStretches[usWidthClass]; + CFRelease(os2); + + // don't use secondary weights in the event of special predefined names + psname = [d postScriptName]; + for (ex = exceptions; *ex != NULL; ex++) + if (CFEqual(psname, *ex)) { + *hasWeight = NO; + break; + } +} + +static BOOL testTTFOTFSubfamilyName(CFStringRef name, CFStringRef want) +{ + CFRange range; + + if (name == NULL) + return NO; + range.location = 0; + range.length = CFStringGetLength(name); + return CFStringFindWithOptions(name, want, range, + (kCFCompareCaseInsensitive | kCFCompareBackwards | kCFCompareNonliteral), NULL) != false; +} + +static BOOL testTTFOTFSubfamilyNames(uiprivFontStyleData *d, CFStringRef want) +{ + switch ([d fontFormat]) { + case kCTFontFormatOpenTypePostScript: + case kCTFontFormatOpenTypeTrueType: + case kCTFontFormatTrueType: + break; + default: + return NO; + } + + if (testTTFOTFSubfamilyName([d preferredSubFamilyName], want)) + return YES; + if (testTTFOTFSubfamilyName([d subFamilyName], want)) + return YES; + if (testTTFOTFSubfamilyName([d fullName], want)) + return YES; + if (testTTFOTFSubfamilyName([d preferredFamilyName], want)) + return YES; + return testTTFOTFSubfamilyName([d familyName], want); +} + +// work around a bug in libFontRegistry.dylib +static BOOL shouldReallyBeThin(uiprivFontStyleData *d) +{ + return testTTFOTFSubfamilyNames(d, CFSTR("W1")); +} + +// work around a bug in libFontRegistry.dylib +static BOOL shouldReallyBeSemiCondensed(uiprivFontStyleData *d) +{ + return testTTFOTFSubfamilyNames(d, CFSTR("Semi Condensed")); +} + +void uiprivProcessFontTraits(uiprivFontStyleData *d, uiFontDescriptor *out) +{ + double weight, width; + BOOL hasWeight, hasWidth; + + hasWeight = NO; + hasWidth = NO; + trySecondaryOS2Values(d, out, &hasWeight, &hasWidth); + + weight = [d weight]; + width = [d width]; + + if (!hasWeight) + // TODO this scale is a bit lopsided + if (weight <= -0.7) + out->Weight = uiTextWeightThin; + else if (weight <= -0.5) + out->Weight = uiTextWeightUltraLight; + else if (weight <= -0.3) + out->Weight = uiTextWeightLight; + else if (weight <= -0.23) { + out->Weight = uiTextWeightBook; + if (shouldReallyBeThin(d)) + out->Weight = uiTextWeightThin; + } else if (weight <= 0.0) + out->Weight = uiTextWeightNormal; + else if (weight <= 0.23) + out->Weight = uiTextWeightMedium; + else if (weight <= 0.3) + out->Weight = uiTextWeightSemiBold; + else if (weight <= 0.4) + out->Weight = uiTextWeightBold; + else if (weight <= 0.5) + out->Weight = uiTextWeightUltraBold; + else if (weight <= 0.7) + out->Weight = uiTextWeightHeavy; + else + out->Weight = uiTextWeightUltraHeavy; + + if (!hasWidth) + // TODO this scale is a bit lopsided + if (width <= -0.7) { + out->Stretch = uiTextStretchUltraCondensed; + if (shouldReallyBeSemiCondensed(d)) + out->Stretch = uiTextStretchSemiCondensed; + } else if (width <= -0.5) + out->Stretch = uiTextStretchExtraCondensed; + else if (width <= -0.2) + out->Stretch = uiTextStretchCondensed; + else if (width <= -0.1) + out->Stretch = uiTextStretchSemiCondensed; + else if (width <= 0.0) + out->Stretch = uiTextStretchNormal; + else if (width <= 0.1) + out->Stretch = uiTextStretchSemiExpanded; + else if (width <= 0.2) + out->Stretch = uiTextStretchExpanded; + else if (width <= 0.6) + out->Stretch = uiTextStretchExtraExpanded; + else + out->Stretch = uiTextStretchUltraExpanded; +} diff --git a/dep/libui/darwin/fontvariation.m b/dep/libui/darwin/fontvariation.m new file mode 100644 index 0000000..6dfb3ab --- /dev/null +++ b/dep/libui/darwin/fontvariation.m @@ -0,0 +1,336 @@ +// 2 november 2017 +#import "uipriv_darwin.h" +#import "attrstr.h" + +// This is the part of the font style matching and normalization code +// that handles fonts that use the fvar table. +// +// Matching stupidity: Core Text **doesn't even bother** matching +// these, even if you tell it to do so explicitly. It'll always return +// all variations for a given font. +// +// Normalization stupidity: Core Text doesn't normalize the fvar +// table values for us, so we'll have to do it ourselves. Furthermore, +// Core Text doesn't provide an API for accessing the avar table, if +// any, so we must do so ourselves. (TODO does Core Text even +// follow the avar table if a font has it?) +// +// Thankfully, normalization is well-defined in both TrueType and +// OpenType and seems identical in both, so we can just normalize +// the values and then convert them linearly to libui values for +// matching. +// +// References: +// - https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6fvar.html +// - https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6avar.html +// - https://www.microsoft.com/typography/otspec/fvar.htm +// - https://www.microsoft.com/typography/otspec/otvaroverview.htm#CSN +// - https://www.microsoft.com/typography/otspec/otff.htm +// - https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6.html#Types +// - https://www.microsoft.com/typography/otspec/avar.htm + +// TODO Skia doesn't quite map correctly; notice what passes for condensed in the drawtext example +// TODO also investigate Marker Felt not working right in Thin and Wide modes (but that's probably the other file, putting it here just so I don't forget) + +#define fvarWeight 0x77676874 +#define fvarWidth 0x77647468 + +// TODO explain why these are signed +typedef int32_t fixed1616; +typedef int16_t fixed214; + +// note that Microsoft's data type list implies that *all* fixed-point types have the same format; it only gives specific examples for the 2.14 format, which confused me because I thought 16.16 worked differently, but eh +static fixed1616 doubleToFixed1616(double d) +{ + double ipart, fpart; + long flong; + int16_t i16; + uint32_t ret; + + fpart = modf(d, &ipart); + // fpart must be unsigned; modf() gives us fpart with the same sign as d (so we have to adjust both ipart and fpart appropriately) + if (fpart < 0) { + ipart -= 1; + fpart = 1 + fpart; + } + fpart *= 65536; + flong = lround(fpart); + i16 = (int16_t) ipart; + ret = (uint32_t) ((uint16_t) i16); + ret <<= 16; + ret |= (uint16_t) (flong & 0xFFFF); + return (fixed1616) ret; +} + +// see also https://stackoverflow.com/questions/8506317/fixed-point-unsigned-division-in-c and freetype's FT_DivFix() +// TODO figure out the specifics of freetype's more complex implementation that shifts b and juggles signs +static fixed1616 fixed1616Divide(fixed1616 a, fixed1616 b) +{ + uint32_t u; + int64_t a64; + + u = (uint32_t) a; + a64 = (int64_t) (((uint64_t) u) << 16); + return (fixed1616) (a64 / b); +} + +static fixed214 fixed1616ToFixed214(fixed1616 f) +{ + uint32_t t; + uint32_t topbit; + + t = (uint32_t) (f + 0x00000002); + topbit = t & 0x80000000; + t >>= 2; + if (topbit != 0) + t |= 0xC000000; + return (fixed214) (t & 0xFFFF); +} + +static double fixed214ToDouble(fixed214 f) +{ + uint16_t u; + double base; + double frac; + + u = (uint16_t) f; + switch ((u >> 14) & 0x3) { + case 0: + base = 0; + break; + case 1: + base = 1; + break; + case 2: + base = -2; + break; + case 3: + base = -1; + } + frac = ((double) (u & 0x3FFF)) / 16384; + return base + frac; +} + +static fixed1616 fixed214ToFixed1616(fixed214 f) +{ + int32_t t; + + t = (int32_t) ((int16_t) f); + t <<= 2; + return (fixed1616) (t - 0x00000002); +} + +static const fixed1616 fixed1616Negative1 = (int32_t) ((uint32_t) 0xFFFF0000); +static const fixed1616 fixed1616Zero = 0x00000000; +static const fixed1616 fixed1616Positive1 = 0x00010000; + +static fixed1616 fixed1616Normalize(fixed1616 val, fixed1616 min, fixed1616 max, fixed1616 def) +{ + if (val < min) + val = min; + if (val > max) + val = max; + if (val < def) + return fixed1616Divide(-(def - val), (def - min)); + if (val > def) + return fixed1616Divide((val - def), (max - def)); + return fixed1616Zero; +} + +static fixed214 normalizedTo214(fixed1616 val, const fixed1616 *avarMappings, size_t avarCount) +{ + if (val < fixed1616Negative1) + val = fixed1616Negative1; + if (val > fixed1616Positive1) + val = fixed1616Positive1; + if (avarCount != 0) { + size_t start, end; + fixed1616 startFrom, endFrom; + fixed1616 startTo, endTo; + + for (end = 0; end < avarCount; end += 2) { + endFrom = avarMappings[end]; + endTo = avarMappings[end + 1]; + if (endFrom >= val) + break; + } + if (endFrom == val) + val = endTo; + else { + start = end - 2; + startFrom = avarMappings[start]; + startTo = avarMappings[start + 1]; + val = fixed1616Divide((val - startFrom), (endFrom - startFrom)); + // TODO find a font with an avar table and make sure this works, or if we need to use special code for this too + val *= (endTo - startTo); + val += startTo; + } + } + return fixed1616ToFixed214(val); +} + +static fixed1616 *avarExtract(CFDataRef table, CFIndex index, size_t *n) +{ + const UInt8 *b; + size_t off; + size_t i, nEntries; + fixed1616 *entries; + fixed1616 *p; + + b = CFDataGetBytePtr(table); + off = 8; +#define nextuint16be() ((((uint16_t) (b[off])) << 8) | ((uint16_t) (b[off + 1]))) + for (; index > 0; index--) { + nEntries = (size_t) nextuint16be(); + off += 2; + off += 4 * nEntries; + } + nEntries = nextuint16be(); + *n = nEntries * 2; + entries = (fixed1616 *) uiprivAlloc(*n * sizeof (fixed1616), "fixed1616[]"); + p = entries; + for (i = 0; i < *n; i++) { + *p++ = fixed214ToFixed1616((fixed214) nextuint16be()); + off += 2; + } + return entries; +} + +static BOOL extractAxisDictValue(CFDictionaryRef dict, CFStringRef key, fixed1616 *out) +{ + CFNumberRef num; + double v; + + num = (CFNumberRef) CFDictionaryGetValue(dict, key); + if (CFNumberGetValue(num, kCFNumberDoubleType, &v) == false) + return NO; + *out = doubleToFixed1616(v); + return YES; +} + +// TODO here and elsewhere: make sure all Objective-C classes and possibly also custom method names have uipriv prefixes +@interface fvarAxis : NSObject { + fixed1616 min; + fixed1616 max; + fixed1616 def; + fixed1616 *avarMappings; + size_t avarCount; +} +- (id)initWithIndex:(CFIndex)i dict:(CFDictionaryRef)dict avarTable:(CFDataRef)table; +- (double)normalize:(double)v; +@end + +@implementation fvarAxis + +- (id)initWithIndex:(CFIndex)i dict:(CFDictionaryRef)dict avarTable:(CFDataRef)table +{ + self = [super init]; + if (self) { + self->avarMappings = NULL; + self->avarCount = 0; + if (!extractAxisDictValue(dict, kCTFontVariationAxisMinimumValueKey, &(self->min))) + goto fail; + if (!extractAxisDictValue(dict, kCTFontVariationAxisMaximumValueKey, &(self->max))) + goto fail; + if (!extractAxisDictValue(dict, kCTFontVariationAxisDefaultValueKey, &(self->def))) + goto fail; + if (table != NULL) + self->avarMappings = avarExtract(table, i, &(self->avarCount)); + } + return self; + +fail: + [self release]; + return nil; +} + +- (void)dealloc +{ + if (self->avarMappings != NULL) { + uiprivFree(self->avarMappings); + self->avarMappings = NULL; + } + [super dealloc]; +} + +- (double)normalize:(double)d +{ + fixed1616 n; + fixed214 n2; + + n = doubleToFixed1616(d); + n = fixed1616Normalize(n, self->min, self->max, self->def); + n2 = normalizedTo214(n, self->avarMappings, self->avarCount); + return fixed214ToDouble(n2); +} + +@end + +NSDictionary *uiprivMakeVariationAxisDict(CFArrayRef axes, CFDataRef avarTable) +{ + CFDictionaryRef axis; + CFIndex i, n; + NSMutableDictionary *out; + + n = CFArrayGetCount(axes); + out = [NSMutableDictionary new]; + for (i = 0; i < n; i++) { + CFNumberRef key; + + axis = (CFDictionaryRef) CFArrayGetValueAtIndex(axes, i); + key = (CFNumberRef) CFDictionaryGetValue(axis, kCTFontVariationAxisIdentifierKey); + [out setObject:[[fvarAxis alloc] initWithIndex:i dict:axis avarTable:avarTable] + forKey:((NSNumber *) key)]; + } + if (avarTable != NULL) + CFRelease(avarTable); + return out; +} + +#define fvarAxisKey(n) [NSNumber numberWithUnsignedInteger:n] + +static BOOL tryAxis(NSDictionary *axisDict, CFDictionaryRef var, NSNumber *key, double *out) +{ + fvarAxis *axis; + CFNumberRef num; + + axis = (fvarAxis *) [axisDict objectForKey:key]; + if (axis == nil) + return NO; + num = (CFNumberRef) CFDictionaryGetValue(var, (CFNumberRef) key); + if (num == nil) + return NO; + if (CFNumberGetValue(num, kCFNumberDoubleType, out) == false) { + // TODO + return NO; + } + *out = [axis normalize:*out]; + return YES; +} + +void uiprivProcessFontVariation(uiprivFontStyleData *d, NSDictionary *axisDict, uiFontDescriptor *out) +{ + CFDictionaryRef var; + double v; + + out->Weight = uiTextWeightNormal; + out->Stretch = uiTextStretchNormal; + + var = [d variation]; + + if (tryAxis(axisDict, var, fvarAxisKey(fvarWeight), &v)) { + // v is now a value between -1 and 1 scaled linearly between discrete points + // we want a linear value between 0 and 1000 with 400 being normal + if (v < 0) { + v += 1; + out->Weight = (uiTextWeight) (v * 400); + } else if (v > 0) + out->Weight += (uiTextWeight) (v * 600); + } + + if (tryAxis(axisDict, var, fvarAxisKey(fvarWidth), &v)) { + // likewise, but with stretches, we go from 0 to 8 with 4 being directly between the two, so this is sufficient + v += 1; + out->Stretch = (uiTextStretch) (v * 4); + } +} diff --git a/dep/libui/darwin/form.m b/dep/libui/darwin/form.m new file mode 100644 index 0000000..af50e36 --- /dev/null +++ b/dep/libui/darwin/form.m @@ -0,0 +1,561 @@ +// 7 june 2016 +#import "uipriv_darwin.h" + +// TODO in the test program, sometimes one of the radio buttons can disappear (try when spaced) + +@interface formChild : NSView +@property uiControl *c; +@property (strong) NSTextField *label; +@property BOOL stretchy; +@property NSLayoutPriority oldHorzHuggingPri; +@property NSLayoutPriority oldVertHuggingPri; +@property (strong) NSLayoutConstraint *baseline; +@property (strong) NSLayoutConstraint *leading; +@property (strong) NSLayoutConstraint *top; +@property (strong) NSLayoutConstraint *trailing; +@property (strong) NSLayoutConstraint *bottom; +- (id)initWithLabel:(NSTextField *)l; +- (void)onDestroy; +- (NSView *)view; +@end + +@interface formView : NSView { + uiForm *f; + NSMutableArray *children; + int padded; + + NSLayoutConstraint *first; + NSMutableArray *inBetweens; + NSLayoutConstraint *last; + NSMutableArray *widths; + NSMutableArray *leadings; + NSMutableArray *middles; + NSMutableArray *trailings; +} +- (id)initWithF:(uiForm *)ff; +- (void)onDestroy; +- (void)removeOurConstraints; +- (void)syncEnableStates:(int)enabled; +- (CGFloat)paddingAmount; +- (void)establishOurConstraints; +- (void)append:(NSString *)label c:(uiControl *)c stretchy:(int)stretchy; +- (void)delete:(int)n; +- (int)isPadded; +- (void)setPadded:(int)p; +- (BOOL)hugsTrailing; +- (BOOL)hugsBottom; +- (int)nStretchy; +@end + +struct uiForm { + uiDarwinControl c; + formView *view; +}; + +@implementation formChild + +- (id)initWithLabel:(NSTextField *)l +{ + self = [super initWithFrame:NSZeroRect]; + if (self) { + self.label = l; + [self.label setTranslatesAutoresizingMaskIntoConstraints:NO]; + [self.label setContentHuggingPriority:NSLayoutPriorityRequired forOrientation:NSLayoutConstraintOrientationHorizontal]; + [self.label setContentHuggingPriority:NSLayoutPriorityRequired forOrientation:NSLayoutConstraintOrientationVertical]; + [self.label setContentCompressionResistancePriority:NSLayoutPriorityRequired forOrientation:NSLayoutConstraintOrientationHorizontal]; + [self.label setContentCompressionResistancePriority:NSLayoutPriorityRequired forOrientation:NSLayoutConstraintOrientationVertical]; + [self addSubview:self.label]; + + self.leading = uiprivMkConstraint(self.label, NSLayoutAttributeLeading, + NSLayoutRelationGreaterThanOrEqual, + self, NSLayoutAttributeLeading, + 1, 0, + @"uiForm label leading"); + [self addConstraint:self.leading]; + self.top = uiprivMkConstraint(self.label, NSLayoutAttributeTop, + NSLayoutRelationEqual, + self, NSLayoutAttributeTop, + 1, 0, + @"uiForm label top"); + [self addConstraint:self.top]; + self.trailing = uiprivMkConstraint(self.label, NSLayoutAttributeTrailing, + NSLayoutRelationEqual, + self, NSLayoutAttributeTrailing, + 1, 0, + @"uiForm label trailing"); + [self addConstraint:self.trailing]; + self.bottom = uiprivMkConstraint(self.label, NSLayoutAttributeBottom, + NSLayoutRelationEqual, + self, NSLayoutAttributeBottom, + 1, 0, + @"uiForm label bottom"); + [self addConstraint:self.bottom]; + } + return self; +} + +- (void)onDestroy +{ + [self removeConstraint:self.trailing]; + self.trailing = nil; + [self removeConstraint:self.top]; + self.top = nil; + [self removeConstraint:self.bottom]; + self.bottom = nil; + + [self.label removeFromSuperview]; + self.label = nil; +} + +- (NSView *)view +{ + return (NSView *) uiControlHandle(self.c); +} + +@end + +@implementation formView + +- (id)initWithF:(uiForm *)ff +{ + self = [super initWithFrame:NSZeroRect]; + if (self != nil) { + self->f = ff; + self->padded = 0; + self->children = [NSMutableArray new]; + + self->inBetweens = [NSMutableArray new]; + self->widths = [NSMutableArray new]; + self->leadings = [NSMutableArray new]; + self->middles = [NSMutableArray new]; + self->trailings = [NSMutableArray new]; + } + return self; +} + +- (void)onDestroy +{ + formChild *fc; + + [self removeOurConstraints]; + [self->inBetweens release]; + [self->widths release]; + [self->leadings release]; + [self->middles release]; + [self->trailings release]; + + for (fc in self->children) { + [self removeConstraint:fc.baseline]; + fc.baseline = nil; + uiControlSetParent(fc.c, NULL); + uiDarwinControlSetSuperview(uiDarwinControl(fc.c), nil); + uiControlDestroy(fc.c); + [fc onDestroy]; + [fc removeFromSuperview]; + } + [self->children release]; +} + +- (void)removeOurConstraints +{ + if (self->first != nil) { + [self removeConstraint:self->first]; + [self->first release]; + self->first = nil; + } + if ([self->inBetweens count] != 0) { + [self removeConstraints:self->inBetweens]; + [self->inBetweens removeAllObjects]; + } + if (self->last != nil) { + [self removeConstraint:self->last]; + [self->last release]; + self->last = nil; + } + if ([self->widths count] != 0) { + [self removeConstraints:self->widths]; + [self->widths removeAllObjects]; + } + if ([self->leadings count] != 0) { + [self removeConstraints:self->leadings]; + [self->leadings removeAllObjects]; + } + if ([self->middles count] != 0) { + [self removeConstraints:self->middles]; + [self->middles removeAllObjects]; + } + if ([self->trailings count] != 0) { + [self removeConstraints:self->trailings]; + [self->trailings removeAllObjects]; + } +} + +- (void)syncEnableStates:(int)enabled +{ + formChild *fc; + + for (fc in self->children) + uiDarwinControlSyncEnableState(uiDarwinControl(fc.c), enabled); +} + +- (CGFloat)paddingAmount +{ + if (!self->padded) + return 0.0; + return uiDarwinPaddingAmount(NULL); +} + +- (void)establishOurConstraints +{ + formChild *fc; + CGFloat padding; + NSView *prev, *prevlabel; + NSLayoutConstraint *c; + + [self removeOurConstraints]; + if ([self->children count] == 0) + return; + padding = [self paddingAmount]; + + // first arrange the children vertically and make them the same width + prev = nil; + for (fc in self->children) { + [fc setHidden:!uiControlVisible(fc.c)]; + if (!uiControlVisible(fc.c)) + continue; + if (prev == nil) { // first view + self->first = uiprivMkConstraint(self, NSLayoutAttributeTop, + NSLayoutRelationEqual, + [fc view], NSLayoutAttributeTop, + 1, 0, + @"uiForm first vertical constraint"); + [self addConstraint:self->first]; + [self->first retain]; + prev = [fc view]; + prevlabel = fc; + continue; + } + // not the first; link it + c = uiprivMkConstraint(prev, NSLayoutAttributeBottom, + NSLayoutRelationEqual, + [fc view], NSLayoutAttributeTop, + 1, -padding, + @"uiForm in-between vertical constraint"); + [self addConstraint:c]; + [self->inBetweens addObject:c]; + // and make the same width + c = uiprivMkConstraint(prev, NSLayoutAttributeWidth, + NSLayoutRelationEqual, + [fc view], NSLayoutAttributeWidth, + 1, 0, + @"uiForm control width constraint"); + [self addConstraint:c]; + [self->widths addObject:c]; + c = uiprivMkConstraint(prevlabel, NSLayoutAttributeWidth, + NSLayoutRelationEqual, + fc, NSLayoutAttributeWidth, + 1, 0, + @"uiForm label lwidth constraint"); + [self addConstraint:c]; + [self->widths addObject:c]; + prev = [fc view]; + prevlabel = fc; + } + if (prev == nil) // all hidden; act as if nothing there + return; + self->last = uiprivMkConstraint(prev, NSLayoutAttributeBottom, + NSLayoutRelationEqual, + self, NSLayoutAttributeBottom, + 1, 0, + @"uiForm last vertical constraint"); + [self addConstraint:self->last]; + [self->last retain]; + + // now arrange the controls horizontally + for (fc in self->children) { + if (!uiControlVisible(fc.c)) + continue; + c = uiprivMkConstraint(self, NSLayoutAttributeLeading, + NSLayoutRelationEqual, + fc, NSLayoutAttributeLeading, + 1, 0, + @"uiForm leading constraint"); + [self addConstraint:c]; + [self->leadings addObject:c]; + // coerce the control to be as wide as possible + // see http://stackoverflow.com/questions/37710892/in-auto-layout-i-set-up-labels-that-shouldnt-grow-horizontally-and-controls-th + c = uiprivMkConstraint(self, NSLayoutAttributeLeading, + NSLayoutRelationEqual, + [fc view], NSLayoutAttributeLeading, + 1, 0, + @"uiForm leading constraint"); + [c setPriority:NSLayoutPriorityDefaultHigh]; + [self addConstraint:c]; + [self->leadings addObject:c]; + c = uiprivMkConstraint(fc, NSLayoutAttributeTrailing, + NSLayoutRelationEqual, + [fc view], NSLayoutAttributeLeading, + 1, -padding, + @"uiForm middle constraint"); + [self addConstraint:c]; + [self->middles addObject:c]; + c = uiprivMkConstraint([fc view], NSLayoutAttributeTrailing, + NSLayoutRelationEqual, + self, NSLayoutAttributeTrailing, + 1, 0, + @"uiForm trailing constraint"); + [self addConstraint:c]; + [self->trailings addObject:c]; + // TODO + c = uiprivMkConstraint(fc, NSLayoutAttributeBottom, + NSLayoutRelationLessThanOrEqual, + self, NSLayoutAttributeBottom, + 1, 0, + @"TODO"); + [self addConstraint:c]; + [self->trailings addObject:c]; + } + + // and make all stretchy controls have the same height + prev = nil; + for (fc in self->children) { + if (!uiControlVisible(fc.c)) + continue; + if (!fc.stretchy) + continue; + if (prev == nil) { + prev = [fc view]; + continue; + } + c = uiprivMkConstraint([fc view], NSLayoutAttributeHeight, + NSLayoutRelationEqual, + prev, NSLayoutAttributeHeight, + 1, 0, + @"uiForm stretchy constraint"); + [self addConstraint:c]; + // TODO make a dedicated array for this + [self->leadings addObject:c]; + } + + // we don't arrange the labels vertically; that's done when we add the control since those constraints don't need to change (they just need to be at their baseline) +} + +- (void)append:(NSString *)label c:(uiControl *)c stretchy:(int)stretchy +{ + formChild *fc; + NSLayoutPriority priority; + NSLayoutAttribute attribute; + int oldnStretchy; + + fc = [[formChild alloc] initWithLabel:uiprivNewLabel(label)]; + fc.c = c; + fc.stretchy = stretchy; + fc.oldHorzHuggingPri = uiDarwinControlHuggingPriority(uiDarwinControl(fc.c), NSLayoutConstraintOrientationHorizontal); + fc.oldVertHuggingPri = uiDarwinControlHuggingPriority(uiDarwinControl(fc.c), NSLayoutConstraintOrientationVertical); + [fc setTranslatesAutoresizingMaskIntoConstraints:NO]; + [self addSubview:fc]; + + uiControlSetParent(fc.c, uiControl(self->f)); + uiDarwinControlSetSuperview(uiDarwinControl(fc.c), self); + uiDarwinControlSyncEnableState(uiDarwinControl(fc.c), uiControlEnabledToUser(uiControl(self->f))); + + // if a control is stretchy, it should not hug vertically + // otherwise, it should *forcibly* hug + if (fc.stretchy) + priority = NSLayoutPriorityDefaultLow; + else + // LONGTERM will default high work? + priority = NSLayoutPriorityRequired; + uiDarwinControlSetHuggingPriority(uiDarwinControl(fc.c), priority, NSLayoutConstraintOrientationVertical); + // make sure controls don't hug their horizontal direction so they fill the width of the view + uiDarwinControlSetHuggingPriority(uiDarwinControl(fc.c), NSLayoutPriorityDefaultLow, NSLayoutConstraintOrientationHorizontal); + + // and constrain the baselines to position the label vertically + // if the view is a scroll view, align tops, not baselines + // this is what Interface Builder does + attribute = NSLayoutAttributeBaseline; + if ([[fc view] isKindOfClass:[NSScrollView class]]) + attribute = NSLayoutAttributeTop; + fc.baseline = uiprivMkConstraint(fc.label, attribute, + NSLayoutRelationEqual, + [fc view], attribute, + 1, 0, + @"uiForm baseline constraint"); + [self addConstraint:fc.baseline]; + + oldnStretchy = [self nStretchy]; + [self->children addObject:fc]; + + [self establishOurConstraints]; + if (fc.stretchy) + if (oldnStretchy == 0) + uiDarwinNotifyEdgeHuggingChanged(uiDarwinControl(self->f)); + + [fc release]; // we don't need the initial reference now +} + +- (void)delete:(int)n +{ + formChild *fc; + int stretchy; + + fc = (formChild *) [self->children objectAtIndex:n]; + stretchy = fc.stretchy; + + uiControlSetParent(fc.c, NULL); + uiDarwinControlSetSuperview(uiDarwinControl(fc.c), nil); + + uiDarwinControlSetHuggingPriority(uiDarwinControl(fc.c), fc.oldHorzHuggingPri, NSLayoutConstraintOrientationHorizontal); + uiDarwinControlSetHuggingPriority(uiDarwinControl(fc.c), fc.oldVertHuggingPri, NSLayoutConstraintOrientationVertical); + + [fc onDestroy]; + [self->children removeObjectAtIndex:n]; + + [self establishOurConstraints]; + if (stretchy) + if ([self nStretchy] == 0) + uiDarwinNotifyEdgeHuggingChanged(uiDarwinControl(self->f)); +} + +- (int)isPadded +{ + return self->padded; +} + +- (void)setPadded:(int)p +{ + CGFloat padding; + NSLayoutConstraint *c; + + self->padded = p; + padding = [self paddingAmount]; + for (c in self->inBetweens) + [c setConstant:-padding]; + for (c in self->middles) + [c setConstant:-padding]; +} + +- (BOOL)hugsTrailing +{ + return YES; // always hug trailing +} + +- (BOOL)hugsBottom +{ + // only hug if we have stretchy + return [self nStretchy] != 0; +} + +- (int)nStretchy +{ + formChild *fc; + int n; + + n = 0; + for (fc in self->children) { + if (!uiControlVisible(fc.c)) + continue; + if (fc.stretchy) + n++; + } + return n; +} + +@end + +static void uiFormDestroy(uiControl *c) +{ + uiForm *f = uiForm(c); + + [f->view onDestroy]; + [f->view release]; + uiFreeControl(uiControl(f)); +} + +uiDarwinControlDefaultHandle(uiForm, view) +uiDarwinControlDefaultParent(uiForm, view) +uiDarwinControlDefaultSetParent(uiForm, view) +uiDarwinControlDefaultToplevel(uiForm, view) +uiDarwinControlDefaultVisible(uiForm, view) +uiDarwinControlDefaultShow(uiForm, view) +uiDarwinControlDefaultHide(uiForm, view) +uiDarwinControlDefaultEnabled(uiForm, view) +uiDarwinControlDefaultEnable(uiForm, view) +uiDarwinControlDefaultDisable(uiForm, view) + +static void uiFormSyncEnableState(uiDarwinControl *c, int enabled) +{ + uiForm *f = uiForm(c); + + if (uiDarwinShouldStopSyncEnableState(uiDarwinControl(f), enabled)) + return; + [f->view syncEnableStates:enabled]; +} + +uiDarwinControlDefaultSetSuperview(uiForm, view) + +static BOOL uiFormHugsTrailingEdge(uiDarwinControl *c) +{ + uiForm *f = uiForm(c); + + return [f->view hugsTrailing]; +} + +static BOOL uiFormHugsBottom(uiDarwinControl *c) +{ + uiForm *f = uiForm(c); + + return [f->view hugsBottom]; +} + +static void uiFormChildEdgeHuggingChanged(uiDarwinControl *c) +{ + uiForm *f = uiForm(c); + + [f->view establishOurConstraints]; +} + +uiDarwinControlDefaultHuggingPriority(uiForm, view) +uiDarwinControlDefaultSetHuggingPriority(uiForm, view) + +static void uiFormChildVisibilityChanged(uiDarwinControl *c) +{ + uiForm *f = uiForm(c); + + [f->view establishOurConstraints]; +} + +void uiFormAppend(uiForm *f, const char *label, uiControl *c, int stretchy) +{ + // LONGTERM on other platforms + // or at leat allow this and implicitly turn it into a spacer + if (c == NULL) + uiprivUserBug("You cannot add NULL to a uiForm."); + [f->view append:uiprivToNSString(label) c:c stretchy:stretchy]; +} + +void uiFormDelete(uiForm *f, int n) +{ + [f->view delete:n]; +} + +int uiFormPadded(uiForm *f) +{ + return [f->view isPadded]; +} + +void uiFormSetPadded(uiForm *f, int padded) +{ + [f->view setPadded:padded]; +} + +uiForm *uiNewForm(void) +{ + uiForm *f; + + uiDarwinNewControl(uiForm, f); + + f->view = [[formView alloc] initWithF:f]; + + return f; +} diff --git a/dep/libui/darwin/future.m b/dep/libui/darwin/future.m new file mode 100644 index 0000000..e6d05ef --- /dev/null +++ b/dep/libui/darwin/future.m @@ -0,0 +1,53 @@ +// 19 may 2017 +#import "uipriv_darwin.h" + +// functions and constants FROM THE FUTURE! +// note: for constants, dlsym() returns the address of the constant itself, as if we had done &constantName + +// added in OS X 10.10; we need 10.8 +CFStringRef *uiprivFUTURE_kCTFontOpenTypeFeatureTag = NULL; +CFStringRef *uiprivFUTURE_kCTFontOpenTypeFeatureValue = NULL; + +// added in OS X 10.12; we need 10.8 +CFStringRef *uiprivFUTURE_kCTBackgroundColorAttributeName = NULL; + +// note that we treat any error as "the symbols aren't there" (and don't care if dlclose() failed) +void uiprivLoadFutures(void) +{ + void *handle; + + // dlsym() walks the dependency chain, so opening the current process should be sufficient + handle = dlopen(NULL, RTLD_LAZY); + if (handle == NULL) + return; +#define GET(var, fn) *((void **) (&var)) = dlsym(handle, #fn) + GET(uiprivFUTURE_kCTFontOpenTypeFeatureTag, kCTFontOpenTypeFeatureTag); + GET(uiprivFUTURE_kCTFontOpenTypeFeatureValue, kCTFontOpenTypeFeatureValue); + GET(uiprivFUTURE_kCTBackgroundColorAttributeName, kCTBackgroundColorAttributeName); + dlclose(handle); +} + +// wrappers for methods that exist in the future that we can check for with respondsToSelector: +// keep them in one place for convenience + +// apparently only added in 10.9; we need 10.8 +void uiprivFUTURE_NSLayoutConstraint_setIdentifier(NSLayoutConstraint *constraint, NSString *identifier) +{ + id cid = (id) constraint; + + if ([constraint respondsToSelector:@selector(setIdentifier:)]) + [cid setIdentifier:identifier]; +} + +// added in 10.11; we need 10.8 +// return whether this was done because we recreate its effects if not (see winmoveresize.m) +BOOL uiprivFUTURE_NSWindow_performWindowDragWithEvent(NSWindow *w, NSEvent *initialEvent) +{ + id cw = (id) w; + + if ([w respondsToSelector:@selector(performWindowDragWithEvent:)]) { + [cw performWindowDragWithEvent:initialEvent]; + return YES; + } + return NO; +} diff --git a/dep/libui/darwin/graphemes.m b/dep/libui/darwin/graphemes.m new file mode 100644 index 0000000..a92534f --- /dev/null +++ b/dep/libui/darwin/graphemes.m @@ -0,0 +1,59 @@ +// 3 december 2016 +#import "uipriv_darwin.h" +#import "attrstr.h" + +// CFStringGetRangeOfComposedCharactersAtIndex() is the function for grapheme clusters +// https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Strings/Articles/stringsClusters.html says that this does work on all multi-codepoint graphemes (despite the name), and that this is the preferred function for this particular job anyway + +int uiprivGraphemesTakesUTF16(void) +{ + return 1; +} + +uiprivGraphemes *uiprivNewGraphemes(void *s, size_t len) +{ + uiprivGraphemes *g; + UniChar *str = (UniChar *) s; + CFStringRef cfstr; + size_t ppos, gpos; + CFRange range; + size_t i; + + g = uiprivNew(uiprivGraphemes); + + cfstr = CFStringCreateWithCharactersNoCopy(NULL, str, len, kCFAllocatorNull); + if (cfstr == NULL) { + // TODO + } + + // first figure out how many graphemes there are + g->len = 0; + ppos = 0; + while (ppos < len) { + range = CFStringGetRangeOfComposedCharactersAtIndex(cfstr, ppos); + g->len++; + ppos = range.location + range.length; + } + + g->pointsToGraphemes = (size_t *) uiprivAlloc((len + 1) * sizeof (size_t), "size_t[] (graphemes)"); + g->graphemesToPoints = (size_t *) uiprivAlloc((g->len + 1) * sizeof (size_t), "size_t[] (graphemes)"); + + // now calculate everything + // fortunately due to the use of CFRange we can do this in one loop trivially! + ppos = 0; + gpos = 0; + while (ppos < len) { + range = CFStringGetRangeOfComposedCharactersAtIndex(cfstr, ppos); + for (i = 0; i < range.length; i++) + g->pointsToGraphemes[range.location + i] = gpos; + g->graphemesToPoints[gpos] = range.location; + gpos++; + ppos = range.location + range.length; + } + // and set the last one + g->pointsToGraphemes[ppos] = gpos; + g->graphemesToPoints[gpos] = ppos; + + CFRelease(cfstr); + return g; +} diff --git a/dep/libui/darwin/grid.m b/dep/libui/darwin/grid.m new file mode 100644 index 0000000..4cbf34c --- /dev/null +++ b/dep/libui/darwin/grid.m @@ -0,0 +1,800 @@ +// 11 june 2016 +#import "uipriv_darwin.h" + +// TODO the assorted test doesn't work right at all + +@interface gridChild : NSView +@property uiControl *c; +@property int left; +@property int top; +@property int xspan; +@property int yspan; +@property int hexpand; +@property uiAlign halign; +@property int vexpand; +@property uiAlign valign; + +@property (strong) NSLayoutConstraint *leadingc; +@property (strong) NSLayoutConstraint *topc; +@property (strong) NSLayoutConstraint *trailingc; +@property (strong) NSLayoutConstraint *bottomc; +@property (strong) NSLayoutConstraint *xcenterc; +@property (strong) NSLayoutConstraint *ycenterc; + +@property NSLayoutPriority oldHorzHuggingPri; +@property NSLayoutPriority oldVertHuggingPri; +- (void)setC:(uiControl *)c grid:(uiGrid *)g; +- (void)onDestroy; +- (NSView *)view; +@end + +@interface gridView : NSView { + uiGrid *g; + NSMutableArray *children; + int padded; + + NSMutableArray *edges; + NSMutableArray *inBetweens; + + NSMutableArray *emptyCellViews; +} +- (id)initWithG:(uiGrid *)gg; +- (void)onDestroy; +- (void)removeOurConstraints; +- (void)syncEnableStates:(int)enabled; +- (CGFloat)paddingAmount; +- (void)establishOurConstraints; +- (void)append:(gridChild *)gc; +- (void)insert:(gridChild *)gc after:(uiControl *)c at:(uiAt)at; +- (int)isPadded; +- (void)setPadded:(int)p; +- (BOOL)hugsTrailing; +- (BOOL)hugsBottom; +- (int)nhexpand; +- (int)nvexpand; +@end + +struct uiGrid { + uiDarwinControl c; + gridView *view; +}; + +@implementation gridChild + +- (void)setC:(uiControl *)c grid:(uiGrid *)g +{ + self.c = c; + self.oldHorzHuggingPri = uiDarwinControlHuggingPriority(uiDarwinControl(self.c), NSLayoutConstraintOrientationHorizontal); + self.oldVertHuggingPri = uiDarwinControlHuggingPriority(uiDarwinControl(self.c), NSLayoutConstraintOrientationVertical); + + uiControlSetParent(self.c, uiControl(g)); + uiDarwinControlSetSuperview(uiDarwinControl(self.c), self); + uiDarwinControlSyncEnableState(uiDarwinControl(self.c), uiControlEnabledToUser(uiControl(g))); + + if (self.halign == uiAlignStart || self.halign == uiAlignFill) { + self.leadingc = uiprivMkConstraint(self, NSLayoutAttributeLeading, + NSLayoutRelationEqual, + [self view], NSLayoutAttributeLeading, + 1, 0, + @"uiGrid child horizontal alignment start constraint"); + [self addConstraint:self.leadingc]; + } + if (self.halign == uiAlignCenter) { + self.xcenterc = uiprivMkConstraint(self, NSLayoutAttributeCenterX, + NSLayoutRelationEqual, + [self view], NSLayoutAttributeCenterX, + 1, 0, + @"uiGrid child horizontal alignment center constraint"); + [self addConstraint:self.xcenterc]; + } + if (self.halign == uiAlignEnd || self.halign == uiAlignFill) { + self.trailingc = uiprivMkConstraint(self, NSLayoutAttributeTrailing, + NSLayoutRelationEqual, + [self view], NSLayoutAttributeTrailing, + 1, 0, + @"uiGrid child horizontal alignment end constraint"); + [self addConstraint:self.trailingc]; + } + + if (self.valign == uiAlignStart || self.valign == uiAlignFill) { + self.topc = uiprivMkConstraint(self, NSLayoutAttributeTop, + NSLayoutRelationEqual, + [self view], NSLayoutAttributeTop, + 1, 0, + @"uiGrid child vertical alignment start constraint"); + [self addConstraint:self.topc]; + } + if (self.valign == uiAlignCenter) { + self.ycenterc = uiprivMkConstraint(self, NSLayoutAttributeCenterY, + NSLayoutRelationEqual, + [self view], NSLayoutAttributeCenterY, + 1, 0, + @"uiGrid child vertical alignment center constraint"); + [self addConstraint:self.ycenterc]; + } + if (self.valign == uiAlignEnd || self.valign == uiAlignFill) { + self.bottomc = uiprivMkConstraint(self, NSLayoutAttributeBottom, + NSLayoutRelationEqual, + [self view], NSLayoutAttributeBottom, + 1, 0, + @"uiGrid child vertical alignment end constraint"); + [self addConstraint:self.bottomc]; + } +} + +- (void)onDestroy +{ + if (self.leadingc != nil) { + [self removeConstraint:self.leadingc]; + self.leadingc = nil; + } + if (self.topc != nil) { + [self removeConstraint:self.topc]; + self.topc = nil; + } + if (self.trailingc != nil) { + [self removeConstraint:self.trailingc]; + self.trailingc = nil; + } + if (self.bottomc != nil) { + [self removeConstraint:self.bottomc]; + self.bottomc = nil; + } + if (self.xcenterc != nil) { + [self removeConstraint:self.xcenterc]; + self.xcenterc = nil; + } + if (self.ycenterc != nil) { + [self removeConstraint:self.ycenterc]; + self.ycenterc = nil; + } + + uiControlSetParent(self.c, NULL); + uiDarwinControlSetSuperview(uiDarwinControl(self.c), nil); + uiDarwinControlSetHuggingPriority(uiDarwinControl(self.c), self.oldHorzHuggingPri, NSLayoutConstraintOrientationHorizontal); + uiDarwinControlSetHuggingPriority(uiDarwinControl(self.c), self.oldVertHuggingPri, NSLayoutConstraintOrientationVertical); +} + +- (NSView *)view +{ + return (NSView *) uiControlHandle(self.c); +} + +@end + +@implementation gridView + +- (id)initWithG:(uiGrid *)gg +{ + self = [super initWithFrame:NSZeroRect]; + if (self != nil) { + self->g = gg; + self->padded = 0; + self->children = [NSMutableArray new]; + + self->edges = [NSMutableArray new]; + self->inBetweens = [NSMutableArray new]; + + self->emptyCellViews = [NSMutableArray new]; + } + return self; +} + +- (void)onDestroy +{ + gridChild *gc; + + [self removeOurConstraints]; + [self->edges release]; + [self->inBetweens release]; + + [self->emptyCellViews release]; + + for (gc in self->children) { + [gc onDestroy]; + uiControlDestroy(gc.c); + [gc removeFromSuperview]; + } + [self->children release]; +} + +- (void)removeOurConstraints +{ + NSView *v; + + if ([self->edges count] != 0) { + [self removeConstraints:self->edges]; + [self->edges removeAllObjects]; + } + if ([self->inBetweens count] != 0) { + [self removeConstraints:self->inBetweens]; + [self->inBetweens removeAllObjects]; + } + + for (v in self->emptyCellViews) + [v removeFromSuperview]; + [self->emptyCellViews removeAllObjects]; +} + +- (void)syncEnableStates:(int)enabled +{ + gridChild *gc; + + for (gc in self->children) + uiDarwinControlSyncEnableState(uiDarwinControl(gc.c), enabled); +} + +- (CGFloat)paddingAmount +{ + if (!self->padded) + return 0.0; + return uiDarwinPaddingAmount(NULL); +} + +// LONGTERM stop early if all controls are hidden +- (void)establishOurConstraints +{ + gridChild *gc; + CGFloat padding; + int xmin, ymin; + int xmax, ymax; + int xcount, ycount; + BOOL first; + int **gg; + NSView ***gv; + BOOL **gspan; + int x, y; + int i; + NSLayoutConstraint *c; + int firstx, firsty; + BOOL *hexpand, *vexpand; + BOOL doit; + BOOL onlyEmptyAndSpanning; + + [self removeOurConstraints]; + if ([self->children count] == 0) + return; + padding = [self paddingAmount]; + + // first, figure out the minimum and maximum row and column numbers + // ignore hidden controls + first = YES; + for (gc in self->children) { + // this bit is important: it ensures row ymin and column xmin have at least one cell to draw, so the onlyEmptyAndSpanning logic below will never run on those rows + if (!uiControlVisible(gc.c)) + continue; + if (first) { + xmin = gc.left; + ymin = gc.top; + xmax = gc.left + gc.xspan; + ymax = gc.top + gc.yspan; + first = NO; + continue; + } + if (xmin > gc.left) + xmin = gc.left; + if (ymin > gc.top) + ymin = gc.top; + if (xmax < (gc.left + gc.xspan)) + xmax = gc.left + gc.xspan; + if (ymax < (gc.top + gc.yspan)) + ymax = gc.top + gc.yspan; + } + if (first != NO) // the entire grid is hidden; do nothing + return; + xcount = xmax - xmin; + ycount = ymax - ymin; + + // now build a topological map of the grid gg[y][x] + // also figure out which cells contain spanned views so they can be ignored later + // treat hidden controls by keeping the indices -1 + gg = (int **) uiprivAlloc(ycount * sizeof (int *), "int[][]"); + gspan = (BOOL **) uiprivAlloc(ycount * sizeof (BOOL *), "BOOL[][]"); + for (y = 0; y < ycount; y++) { + gg[y] = (int *) uiprivAlloc(xcount * sizeof (int), "int[]"); + gspan[y] = (BOOL *) uiprivAlloc(xcount * sizeof (BOOL), "BOOL[]"); + for (x = 0; x < xcount; x++) + gg[y][x] = -1; // empty + } + for (i = 0; i < [self->children count]; i++) { + gc = (gridChild *) [self->children objectAtIndex:i]; + if (!uiControlVisible(gc.c)) + continue; + for (y = gc.top; y < gc.top + gc.yspan; y++) + for (x = gc.left; x < gc.left + gc.xspan; x++) { + gg[y - ymin][x - xmin] = i; + if (x != gc.left || y != gc.top) + gspan[y - ymin][x - xmin] = YES; + } + } + + // if a row or column only contains emptys and spanning cells of a opposite-direction spannings, remove it by duplicating the previous row or column + for (y = 0; y < ycount; y++) { + onlyEmptyAndSpanning = YES; + for (x = 0; x < xcount; x++) + if (gg[y][x] != -1) { + gc = (gridChild *) [self->children objectAtIndex:gg[y][x]]; + if (gc.yspan == 1 || gc.top - ymin == y) { + onlyEmptyAndSpanning = NO; + break; + } + } + if (onlyEmptyAndSpanning) + for (x = 0; x < xcount; x++) { + gg[y][x] = gg[y - 1][x]; + gspan[y][x] = YES; + } + } + for (x = 0; x < xcount; x++) { + onlyEmptyAndSpanning = YES; + for (y = 0; y < ycount; y++) + if (gg[y][x] != -1) { + gc = (gridChild *) [self->children objectAtIndex:gg[y][x]]; + if (gc.xspan == 1 || gc.left - xmin == x) { + onlyEmptyAndSpanning = NO; + break; + } + } + if (onlyEmptyAndSpanning) + for (y = 0; y < ycount; y++) { + gg[y][x] = gg[y][x - 1]; + gspan[y][x] = YES; + } + } + + // now build a topological map of the grid's views gv[y][x] + // for any empty cell, create a dummy view + gv = (NSView ***) uiprivAlloc(ycount * sizeof (NSView **), "NSView *[][]"); + for (y = 0; y < ycount; y++) { + gv[y] = (NSView **) uiprivAlloc(xcount * sizeof (NSView *), "NSView *[]"); + for (x = 0; x < xcount; x++) + if (gg[y][x] == -1) { + gv[y][x] = [[NSView alloc] initWithFrame:NSZeroRect]; + [gv[y][x] setTranslatesAutoresizingMaskIntoConstraints:NO]; + [self addSubview:gv[y][x]]; + [self->emptyCellViews addObject:gv[y][x]]; + } else { + gc = (gridChild *) [self->children objectAtIndex:gg[y][x]]; + gv[y][x] = gc; + } + } + + // now figure out which rows and columns really expand + hexpand = (BOOL *) uiprivAlloc(xcount * sizeof (BOOL), "BOOL[]"); + vexpand = (BOOL *) uiprivAlloc(ycount * sizeof (BOOL), "BOOL[]"); + // first, which don't span + for (gc in self->children) { + if (!uiControlVisible(gc.c)) + continue; + if (gc.hexpand && gc.xspan == 1) + hexpand[gc.left - xmin] = YES; + if (gc.vexpand && gc.yspan == 1) + vexpand[gc.top - ymin] = YES; + } + // second, which do span + // the way we handle this is simple: if none of the spanned rows/columns expand, make all rows/columns expand + for (gc in self->children) { + if (!uiControlVisible(gc.c)) + continue; + if (gc.hexpand && gc.xspan != 1) { + doit = YES; + for (x = gc.left; x < gc.left + gc.xspan; x++) + if (hexpand[x - xmin]) { + doit = NO; + break; + } + if (doit) + for (x = gc.left; x < gc.left + gc.xspan; x++) + hexpand[x - xmin] = YES; + } + if (gc.vexpand && gc.yspan != 1) { + doit = YES; + for (y = gc.top; y < gc.top + gc.yspan; y++) + if (vexpand[y - ymin]) { + doit = NO; + break; + } + if (doit) + for (y = gc.top; y < gc.top + gc.yspan; y++) + vexpand[y - ymin] = YES; + } + } + + // now establish all the edge constraints + // leading and trailing edges + for (y = 0; y < ycount; y++) { + c = uiprivMkConstraint(self, NSLayoutAttributeLeading, + NSLayoutRelationEqual, + gv[y][0], NSLayoutAttributeLeading, + 1, 0, + @"uiGrid leading edge constraint"); + [self addConstraint:c]; + [self->edges addObject:c]; + c = uiprivMkConstraint(self, NSLayoutAttributeTrailing, + NSLayoutRelationEqual, + gv[y][xcount - 1], NSLayoutAttributeTrailing, + 1, 0, + @"uiGrid trailing edge constraint"); + [self addConstraint:c]; + [self->edges addObject:c]; + } + // top and bottom edges + for (x = 0; x < xcount; x++) { + c = uiprivMkConstraint(self, NSLayoutAttributeTop, + NSLayoutRelationEqual, + gv[0][x], NSLayoutAttributeTop, + 1, 0, + @"uiGrid top edge constraint"); + [self addConstraint:c]; + [self->edges addObject:c]; + c = uiprivMkConstraint(self, NSLayoutAttributeBottom, + NSLayoutRelationEqual, + gv[ycount - 1][x], NSLayoutAttributeBottom, + 1, 0, + @"uiGrid bottom edge constraint"); + [self addConstraint:c]; + [self->edges addObject:c]; + } + + // now align leading and top edges + // do NOT align spanning cells! + for (x = 0; x < xcount; x++) { + for (y = 0; y < ycount; y++) + if (!gspan[y][x]) + break; + firsty = y; + for (y++; y < ycount; y++) { + if (gspan[y][x]) + continue; + c = uiprivMkConstraint(gv[firsty][x], NSLayoutAttributeLeading, + NSLayoutRelationEqual, + gv[y][x], NSLayoutAttributeLeading, + 1, 0, + @"uiGrid column leading constraint"); + [self addConstraint:c]; + [self->edges addObject:c]; + } + } + for (y = 0; y < ycount; y++) { + for (x = 0; x < xcount; x++) + if (!gspan[y][x]) + break; + firstx = x; + for (x++; x < xcount; x++) { + if (gspan[y][x]) + continue; + c = uiprivMkConstraint(gv[y][firstx], NSLayoutAttributeTop, + NSLayoutRelationEqual, + gv[y][x], NSLayoutAttributeTop, + 1, 0, + @"uiGrid row top constraint"); + [self addConstraint:c]; + [self->edges addObject:c]; + } + } + + // now string adjacent views together + for (y = 0; y < ycount; y++) + for (x = 1; x < xcount; x++) + if (gv[y][x - 1] != gv[y][x]) { + c = uiprivMkConstraint(gv[y][x - 1], NSLayoutAttributeTrailing, + NSLayoutRelationEqual, + gv[y][x], NSLayoutAttributeLeading, + 1, -padding, + @"uiGrid internal horizontal constraint"); + [self addConstraint:c]; + [self->inBetweens addObject:c]; + } + for (x = 0; x < xcount; x++) + for (y = 1; y < ycount; y++) + if (gv[y - 1][x] != gv[y][x]) { + c = uiprivMkConstraint(gv[y - 1][x], NSLayoutAttributeBottom, + NSLayoutRelationEqual, + gv[y][x], NSLayoutAttributeTop, + 1, -padding, + @"uiGrid internal vertical constraint"); + [self addConstraint:c]; + [self->inBetweens addObject:c]; + } + + // now set priorities for all widgets that expand or not + // if a cell is in an expanding row, OR If it spans, then it must be willing to stretch + // otherwise, it tries not to + // note we don't use NSLayoutPriorityRequired as that will cause things to squish when they shouldn't + for (gc in self->children) { + NSLayoutPriority priority; + + if (!uiControlVisible(gc.c)) + continue; + if (hexpand[gc.left - xmin] || gc.xspan != 1) + priority = NSLayoutPriorityDefaultLow; + else + priority = NSLayoutPriorityDefaultHigh; + uiDarwinControlSetHuggingPriority(uiDarwinControl(gc.c), priority, NSLayoutConstraintOrientationHorizontal); + // same for vertical direction + if (vexpand[gc.top - ymin] || gc.yspan != 1) + priority = NSLayoutPriorityDefaultLow; + else + priority = NSLayoutPriorityDefaultHigh; + uiDarwinControlSetHuggingPriority(uiDarwinControl(gc.c), priority, NSLayoutConstraintOrientationVertical); + } + + // TODO make all expanding rows/columns the same height/width + + // and finally clean up + uiprivFree(hexpand); + uiprivFree(vexpand); + for (y = 0; y < ycount; y++) { + uiprivFree(gg[y]); + uiprivFree(gv[y]); + uiprivFree(gspan[y]); + } + uiprivFree(gg); + uiprivFree(gv); + uiprivFree(gspan); +} + +- (void)append:(gridChild *)gc +{ + BOOL update; + int oldnh, oldnv; + + [gc setTranslatesAutoresizingMaskIntoConstraints:NO]; + [self addSubview:gc]; + + // no need to set priority here; that's done in establishOurConstraints + + oldnh = [self nhexpand]; + oldnv = [self nvexpand]; + [self->children addObject:gc]; + + [self establishOurConstraints]; + update = NO; + if (gc.hexpand) + if (oldnh == 0) + update = YES; + if (gc.vexpand) + if (oldnv == 0) + update = YES; + if (update) + uiDarwinNotifyEdgeHuggingChanged(uiDarwinControl(self->g)); + + [gc release]; // we don't need the initial reference now +} + +- (void)insert:(gridChild *)gc after:(uiControl *)c at:(uiAt)at +{ + gridChild *other; + BOOL found; + + found = NO; + for (other in self->children) + if (other.c == c) { + found = YES; + break; + } + if (!found) + uiprivUserBug("Existing control %p is not in grid %p; you cannot add other controls next to it", c, self->g); + + switch (at) { + case uiAtLeading: + gc.left = other.left - gc.xspan; + gc.top = other.top; + break; + case uiAtTop: + gc.left = other.left; + gc.top = other.top - gc.yspan; + break; + case uiAtTrailing: + gc.left = other.left + other.xspan; + gc.top = other.top; + break; + case uiAtBottom: + gc.left = other.left; + gc.top = other.top + other.yspan; + break; + // TODO add error checks to ALL enums + } + + [self append:gc]; +} + +- (int)isPadded +{ + return self->padded; +} + +- (void)setPadded:(int)p +{ + CGFloat padding; + NSLayoutConstraint *c; + +#if 0 /* TODO */ +dispatch_after( +dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), +dispatch_get_main_queue(), +^{ [[self window] visualizeConstraints:[self constraints]]; } +); +#endif + self->padded = p; + padding = [self paddingAmount]; + for (c in self->inBetweens) + switch ([c firstAttribute]) { + case NSLayoutAttributeLeading: + case NSLayoutAttributeTop: + [c setConstant:padding]; + break; + case NSLayoutAttributeTrailing: + case NSLayoutAttributeBottom: + [c setConstant:-padding]; + break; + } +} + +- (BOOL)hugsTrailing +{ + // only hug if we have horizontally expanding + return [self nhexpand] != 0; +} + +- (BOOL)hugsBottom +{ + // only hug if we have vertically expanding + return [self nvexpand] != 0; +} + +- (int)nhexpand +{ + gridChild *gc; + int n; + + n = 0; + for (gc in self->children) { + if (!uiControlVisible(gc.c)) + continue; + if (gc.hexpand) + n++; + } + return n; +} + +- (int)nvexpand +{ + gridChild *gc; + int n; + + n = 0; + for (gc in self->children) { + if (!uiControlVisible(gc.c)) + continue; + if (gc.vexpand) + n++; + } + return n; +} + +@end + +static void uiGridDestroy(uiControl *c) +{ + uiGrid *g = uiGrid(c); + + [g->view onDestroy]; + [g->view release]; + uiFreeControl(uiControl(g)); +} + +uiDarwinControlDefaultHandle(uiGrid, view) +uiDarwinControlDefaultParent(uiGrid, view) +uiDarwinControlDefaultSetParent(uiGrid, view) +uiDarwinControlDefaultToplevel(uiGrid, view) +uiDarwinControlDefaultVisible(uiGrid, view) +uiDarwinControlDefaultShow(uiGrid, view) +uiDarwinControlDefaultHide(uiGrid, view) +uiDarwinControlDefaultEnabled(uiGrid, view) +uiDarwinControlDefaultEnable(uiGrid, view) +uiDarwinControlDefaultDisable(uiGrid, view) + +static void uiGridSyncEnableState(uiDarwinControl *c, int enabled) +{ + uiGrid *g = uiGrid(c); + + if (uiDarwinShouldStopSyncEnableState(uiDarwinControl(g), enabled)) + return; + [g->view syncEnableStates:enabled]; +} + +uiDarwinControlDefaultSetSuperview(uiGrid, view) + +static BOOL uiGridHugsTrailingEdge(uiDarwinControl *c) +{ + uiGrid *g = uiGrid(c); + + return [g->view hugsTrailing]; +} + +static BOOL uiGridHugsBottom(uiDarwinControl *c) +{ + uiGrid *g = uiGrid(c); + + return [g->view hugsBottom]; +} + +static void uiGridChildEdgeHuggingChanged(uiDarwinControl *c) +{ + uiGrid *g = uiGrid(c); + + [g->view establishOurConstraints]; +} + +uiDarwinControlDefaultHuggingPriority(uiGrid, view) +uiDarwinControlDefaultSetHuggingPriority(uiGrid, view) + +static void uiGridChildVisibilityChanged(uiDarwinControl *c) +{ + uiGrid *g = uiGrid(c); + + [g->view establishOurConstraints]; +} + +static gridChild *toChild(uiControl *c, int xspan, int yspan, int hexpand, uiAlign halign, int vexpand, uiAlign valign, uiGrid *g) +{ + gridChild *gc; + + if (xspan < 0) + uiprivUserBug("You cannot have a negative xspan in a uiGrid cell."); + if (yspan < 0) + uiprivUserBug("You cannot have a negative yspan in a uiGrid cell."); + gc = [gridChild new]; + gc.xspan = xspan; + gc.yspan = yspan; + gc.hexpand = hexpand; + gc.halign = halign; + gc.vexpand = vexpand; + gc.valign = valign; + [gc setC:c grid:g]; + return gc; +} + +void uiGridAppend(uiGrid *g, uiControl *c, int left, int top, int xspan, int yspan, int hexpand, uiAlign halign, int vexpand, uiAlign valign) +{ + gridChild *gc; + + // LONGTERM on other platforms + // or at leat allow this and implicitly turn it into a spacer + if (c == NULL) + uiprivUserBug("You cannot add NULL to a uiGrid."); + gc = toChild(c, xspan, yspan, hexpand, halign, vexpand, valign, g); + gc.left = left; + gc.top = top; + [g->view append:gc]; +} + +void uiGridInsertAt(uiGrid *g, uiControl *c, uiControl *existing, uiAt at, int xspan, int yspan, int hexpand, uiAlign halign, int vexpand, uiAlign valign) +{ + gridChild *gc; + + gc = toChild(c, xspan, yspan, hexpand, halign, vexpand, valign, g); + [g->view insert:gc after:existing at:at]; +} + +int uiGridPadded(uiGrid *g) +{ + return [g->view isPadded]; +} + +void uiGridSetPadded(uiGrid *g, int padded) +{ + [g->view setPadded:padded]; +} + +uiGrid *uiNewGrid(void) +{ + uiGrid *g; + + uiDarwinNewControl(uiGrid, g); + + g->view = [[gridView alloc] initWithG:g]; + + return g; +} diff --git a/dep/libui/darwin/group.m b/dep/libui/darwin/group.m new file mode 100644 index 0000000..2cfcdf4 --- /dev/null +++ b/dep/libui/darwin/group.m @@ -0,0 +1,194 @@ +// 14 august 2015 +#import "uipriv_darwin.h" + +struct uiGroup { + uiDarwinControl c; + NSBox *box; + uiControl *child; + NSLayoutPriority oldHorzHuggingPri; + NSLayoutPriority oldVertHuggingPri; + int margined; + uiprivSingleChildConstraints constraints; + NSLayoutPriority horzHuggingPri; + NSLayoutPriority vertHuggingPri; +}; + +static void removeConstraints(uiGroup *g) +{ + // set to contentView instead of to the box itself, otherwise we get clipping underneath the label + uiprivSingleChildConstraintsRemove(&(g->constraints), [g->box contentView]); +} + +static void uiGroupDestroy(uiControl *c) +{ + uiGroup *g = uiGroup(c); + + removeConstraints(g); + if (g->child != NULL) { + uiControlSetParent(g->child, NULL); + uiDarwinControlSetSuperview(uiDarwinControl(g->child), nil); + uiControlDestroy(g->child); + } + [g->box release]; + uiFreeControl(uiControl(g)); +} + +uiDarwinControlDefaultHandle(uiGroup, box) +uiDarwinControlDefaultParent(uiGroup, box) +uiDarwinControlDefaultSetParent(uiGroup, box) +uiDarwinControlDefaultToplevel(uiGroup, box) +uiDarwinControlDefaultVisible(uiGroup, box) +uiDarwinControlDefaultShow(uiGroup, box) +uiDarwinControlDefaultHide(uiGroup, box) +uiDarwinControlDefaultEnabled(uiGroup, box) +uiDarwinControlDefaultEnable(uiGroup, box) +uiDarwinControlDefaultDisable(uiGroup, box) + +static void uiGroupSyncEnableState(uiDarwinControl *c, int enabled) +{ + uiGroup *g = uiGroup(c); + + if (uiDarwinShouldStopSyncEnableState(uiDarwinControl(g), enabled)) + return; + if (g->child != NULL) + uiDarwinControlSyncEnableState(uiDarwinControl(g->child), enabled); +} + +uiDarwinControlDefaultSetSuperview(uiGroup, box) + +static void groupRelayout(uiGroup *g) +{ + NSView *childView; + + removeConstraints(g); + if (g->child == NULL) + return; + childView = (NSView *) uiControlHandle(g->child); + uiprivSingleChildConstraintsEstablish(&(g->constraints), + [g->box contentView], childView, + uiDarwinControlHugsTrailingEdge(uiDarwinControl(g->child)), + uiDarwinControlHugsBottom(uiDarwinControl(g->child)), + g->margined, + @"uiGroup"); + // needed for some very rare drawing errors... + uiprivJiggleViewLayout(g->box); +} + +// TODO rename these since I'm starting to get confused by what they mean by hugging +BOOL uiGroupHugsTrailingEdge(uiDarwinControl *c) +{ + uiGroup *g = uiGroup(c); + + // TODO make a function? + return g->horzHuggingPri < NSLayoutPriorityWindowSizeStayPut; +} + +BOOL uiGroupHugsBottom(uiDarwinControl *c) +{ + uiGroup *g = uiGroup(c); + + return g->vertHuggingPri < NSLayoutPriorityWindowSizeStayPut; +} + +static void uiGroupChildEdgeHuggingChanged(uiDarwinControl *c) +{ + uiGroup *g = uiGroup(c); + + groupRelayout(g); +} + +static NSLayoutPriority uiGroupHuggingPriority(uiDarwinControl *c, NSLayoutConstraintOrientation orientation) +{ + uiGroup *g = uiGroup(c); + + if (orientation == NSLayoutConstraintOrientationHorizontal) + return g->horzHuggingPri; + return g->vertHuggingPri; +} + +static void uiGroupSetHuggingPriority(uiDarwinControl *c, NSLayoutPriority priority, NSLayoutConstraintOrientation orientation) +{ + uiGroup *g = uiGroup(c); + + if (orientation == NSLayoutConstraintOrientationHorizontal) + g->horzHuggingPri = priority; + else + g->vertHuggingPri = priority; + uiDarwinNotifyEdgeHuggingChanged(uiDarwinControl(g)); +} + +static void uiGroupChildVisibilityChanged(uiDarwinControl *c) +{ + uiGroup *g = uiGroup(c); + + groupRelayout(g); +} + +char *uiGroupTitle(uiGroup *g) +{ + return uiDarwinNSStringToText([g->box title]); +} + +void uiGroupSetTitle(uiGroup *g, const char *title) +{ + [g->box setTitle:uiprivToNSString(title)]; +} + +void uiGroupSetChild(uiGroup *g, uiControl *child) +{ + NSView *childView; + + if (g->child != NULL) { + removeConstraints(g); + uiDarwinControlSetHuggingPriority(uiDarwinControl(g->child), g->oldHorzHuggingPri, NSLayoutConstraintOrientationHorizontal); + uiDarwinControlSetHuggingPriority(uiDarwinControl(g->child), g->oldVertHuggingPri, NSLayoutConstraintOrientationVertical); + uiControlSetParent(g->child, NULL); + uiDarwinControlSetSuperview(uiDarwinControl(g->child), nil); + } + g->child = child; + if (g->child != NULL) { + childView = (NSView *) uiControlHandle(g->child); + uiControlSetParent(g->child, uiControl(g)); + uiDarwinControlSetSuperview(uiDarwinControl(g->child), [g->box contentView]); + uiDarwinControlSyncEnableState(uiDarwinControl(g->child), uiControlEnabledToUser(uiControl(g))); + // don't hug, just in case we're a stretchy group + g->oldHorzHuggingPri = uiDarwinControlHuggingPriority(uiDarwinControl(g->child), NSLayoutConstraintOrientationHorizontal); + g->oldVertHuggingPri = uiDarwinControlHuggingPriority(uiDarwinControl(g->child), NSLayoutConstraintOrientationVertical); + uiDarwinControlSetHuggingPriority(uiDarwinControl(g->child), NSLayoutPriorityDefaultLow, NSLayoutConstraintOrientationHorizontal); + uiDarwinControlSetHuggingPriority(uiDarwinControl(g->child), NSLayoutPriorityDefaultLow, NSLayoutConstraintOrientationVertical); + } + groupRelayout(g); +} + +int uiGroupMargined(uiGroup *g) +{ + return g->margined; +} + +void uiGroupSetMargined(uiGroup *g, int margined) +{ + g->margined = margined; + uiprivSingleChildConstraintsSetMargined(&(g->constraints), g->margined); +} + +uiGroup *uiNewGroup(const char *title) +{ + uiGroup *g; + + uiDarwinNewControl(uiGroup, g); + + g->box = [[NSBox alloc] initWithFrame:NSZeroRect]; + [g->box setTitle:uiprivToNSString(title)]; + [g->box setBoxType:NSBoxPrimary]; + [g->box setBorderType:NSLineBorder]; + [g->box setTransparent:NO]; + [g->box setTitlePosition:NSAtTop]; + // we can't use uiDarwinSetControlFont() because the selector is different + [g->box setTitleFont:[NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:NSSmallControlSize]]]; + + // default to low hugging to not hug edges + g->horzHuggingPri = NSLayoutPriorityDefaultLow; + g->vertHuggingPri = NSLayoutPriorityDefaultLow; + + return g; +} diff --git a/dep/libui/darwin/image.m b/dep/libui/darwin/image.m new file mode 100644 index 0000000..0b10cb0 --- /dev/null +++ b/dep/libui/darwin/image.m @@ -0,0 +1,84 @@ +// 25 june 2016 +#import "uipriv_darwin.h" + +struct uiImage { + NSImage *i; + NSSize size; +}; + +uiImage *uiNewImage(double width, double height) +{ + uiImage *i; + + i = uiprivNew(uiImage); + i->size = NSMakeSize(width, height); + i->i = [[NSImage alloc] initWithSize:i->size]; + return i; +} + +void uiFreeImage(uiImage *i) +{ + [i->i release]; + uiprivFree(i); +} + +void uiImageAppend(uiImage *i, void *pixels, int pixelWidth, int pixelHeight, int byteStride) +{ + NSBitmapImageRep *repCalibrated, *repsRGB; + int x, y; + uint8_t *pix, *data; + NSInteger realStride; + + repCalibrated = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL + pixelsWide:pixelWidth + pixelsHigh:pixelHeight + bitsPerSample:8 + samplesPerPixel:4 + hasAlpha:YES + isPlanar:NO + colorSpaceName:NSCalibratedRGBColorSpace + bitmapFormat:0 + bytesPerRow:0 + bitsPerPixel:32]; + + // Apple doesn't explicitly document this, but we apparently need to use native system endian for the data :| + // TODO split this into a utility routine? + // TODO find proper documentation + // TODO test this on a big-endian system somehow; I have a feeling the above comment is wrong about the diagnosis since the order we are specifying is now 0xAABBGGRR + pix = (uint8_t *) pixels; + data = (uint8_t *) [repCalibrated bitmapData]; + realStride = [repCalibrated bytesPerRow]; + for (y = 0; y < pixelHeight; y++) { + for (x = 0; x < pixelWidth * 4; x += 4) { + union { + uint32_t v32; + uint8_t v8[4]; + } v; + + v.v32 = ((uint32_t) (pix[x + 3])) << 24; + v.v32 |= ((uint32_t) (pix[x + 2])) << 16; + v.v32 |= ((uint32_t) (pix[x + 1])) << 8; + v.v32 |= ((uint32_t) (pix[x])); + data[x] = v.v8[0]; + data[x + 1] = v.v8[1]; + data[x + 2] = v.v8[2]; + data[x + 3] = v.v8[3]; + } + pix += byteStride; + data += realStride; + } + + // we can't call the constructor with this, but we can retag (NOT convert) + repsRGB = [repCalibrated bitmapImageRepByRetaggingWithColorSpace:[NSColorSpace sRGBColorSpace]]; + + [i->i addRepresentation:repsRGB]; + [repsRGB setSize:i->size]; + // don't release repsRGB; it may be equivalent to repCalibrated + // do release repCalibrated though; NSImage has a ref to either it or to repsRGB + [repCalibrated release]; +} + +NSImage *uiprivImageNSImage(uiImage *i) +{ + return i->i; +} diff --git a/dep/libui/darwin/label.m b/dep/libui/darwin/label.m new file mode 100644 index 0000000..942b153 --- /dev/null +++ b/dep/libui/darwin/label.m @@ -0,0 +1,43 @@ +// 14 august 2015 +#import "uipriv_darwin.h" + +struct uiLabel { + uiDarwinControl c; + NSTextField *textfield; +}; + +uiDarwinControlAllDefaults(uiLabel, textfield) + +char *uiLabelText(uiLabel *l) +{ + return uiDarwinNSStringToText([l->textfield stringValue]); +} + +void uiLabelSetText(uiLabel *l, const char *text) +{ + [l->textfield setStringValue:uiprivToNSString(text)]; +} + +NSTextField *uiprivNewLabel(NSString *str) +{ + NSTextField *tf; + + tf = [[NSTextField alloc] initWithFrame:NSZeroRect]; + [tf setStringValue:str]; + [tf setEditable:NO]; + [tf setSelectable:NO]; + [tf setDrawsBackground:NO]; + uiprivFinishNewTextField(tf, NO); + return tf; +} + +uiLabel *uiNewLabel(const char *text) +{ + uiLabel *l; + + uiDarwinNewControl(uiLabel, l); + + l->textfield = uiprivNewLabel(uiprivToNSString(text)); + + return l; +} diff --git a/dep/libui/darwin/main.m b/dep/libui/darwin/main.m new file mode 100644 index 0000000..0d02d64 --- /dev/null +++ b/dep/libui/darwin/main.m @@ -0,0 +1,288 @@ +// 6 april 2015 +#import "uipriv_darwin.h" +#import "attrstr.h" + +static BOOL canQuit = NO; +static NSAutoreleasePool *globalPool; +static uiprivApplicationClass *app; +static uiprivAppDelegate *delegate; + +static BOOL (^isRunning)(void); +static BOOL stepsIsRunning; + +@implementation uiprivApplicationClass + +- (void)sendEvent:(NSEvent *)e +{ + if (uiprivSendAreaEvents(e) != 0) + return; + [super sendEvent:e]; +} + +// NSColorPanel always sends changeColor: to the first responder regardless of whether there's a target set on it +// we can override it here (see colorbutton.m) +// thanks to mikeash in irc.freenode.net/#macdev for informing me this is how the first responder chain is initiated +// it turns out NSFontManager also sends changeFont: through this; let's inhibit that here too (see fontbutton.m) +- (BOOL)sendAction:(SEL)sel to:(id)to from:(id)from +{ + if (uiprivColorButtonInhibitSendAction(sel, from, to)) + return NO; + if (uiprivFontButtonInhibitSendAction(sel, from, to)) + return NO; + return [super sendAction:sel to:to from:from]; +} + +// likewise, NSFontManager also sends NSFontPanelValidation messages to the first responder, however it does NOT use sendAction:from:to:! +// instead, it uses this one (thanks swillits in irc.freenode.net/#macdev) +// we also need to override it (see fontbutton.m) +- (id)targetForAction:(SEL)sel to:(id)to from:(id)from +{ + id override; + + if (uiprivFontButtonOverrideTargetForAction(sel, from, to, &override)) + return override; + return [super targetForAction:sel to:to from:from]; +} + +// hey look! we're overriding terminate:! +// we're going to make sure we can go back to main() whether Cocoa likes it or not! +// and just how are we going to do that, hm? +// (note: this is called after applicationShouldTerminate:) +- (void)terminate:(id)sender +{ + // yes that's right folks: DO ABSOLUTELY NOTHING. + // the magic is [NSApp run] will just... stop. + + // well let's not do nothing; let's actually quit our graceful way + NSEvent *e; + + if (!canQuit) + uiprivImplBug("call to [NSApp terminate:] when not ready to terminate; definitely contact andlabs"); + + [uiprivNSApp() stop:uiprivNSApp()]; + // stop: won't register until another event has passed; let's synthesize one + e = [NSEvent otherEventWithType:NSApplicationDefined + location:NSZeroPoint + modifierFlags:0 + timestamp:[[NSProcessInfo processInfo] systemUptime] + windowNumber:0 + context:[NSGraphicsContext currentContext] + subtype:0 + data1:0 + data2:0]; + [uiprivNSApp() postEvent:e atStart:NO]; // let pending events take priority (this is what PostQuitMessage() on Windows does so we have to do it here too for parity; thanks to mikeash in irc.freenode.net/#macdev for confirming that this parameter should indeed be NO) + + // and in case uiMainSteps() was called + stepsIsRunning = NO; +} + +@end + +@implementation uiprivAppDelegate + +- (void)dealloc +{ + // Apple docs: "Don't Use Accessor Methods in Initializer Methods and dealloc" + [_menuManager release]; + [super dealloc]; +} + +- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)app +{ + // for debugging + NSLog(@"in applicationShouldTerminate:"); + if (uiprivShouldQuit()) { + canQuit = YES; + // this will call terminate:, which is the same as uiQuit() + return NSTerminateNow; + } + return NSTerminateCancel; +} + +- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)app +{ + return NO; +} + +@end + +uiInitOptions uiprivOptions; + +const char *uiInit(uiInitOptions *o) +{ + @autoreleasepool { + uiprivOptions = *o; + app = [[uiprivApplicationClass sharedApplication] retain]; + // don't check for a NO return; something (launch services?) causes running from application bundles to always return NO when asking to change activation policy, even if the change is to the same activation policy! + // see https://github.com/andlabs/ui/issues/6 + [uiprivNSApp() setActivationPolicy:NSApplicationActivationPolicyRegular]; + delegate = [uiprivAppDelegate new]; + [uiprivNSApp() setDelegate:delegate]; + + uiprivInitAlloc(); + uiprivLoadFutures(); + uiprivLoadUndocumented(); + + // always do this so we always have an application menu + uiprivAppDelegate().menuManager = [[uiprivMenuManager new] autorelease]; + [uiprivNSApp() setMainMenu:[uiprivAppDelegate().menuManager makeMenubar]]; + + uiprivSetupFontPanel(); + + uiprivInitUnderlineColors(); + } + + globalPool = [[NSAutoreleasePool alloc] init]; + + return NULL; +} + +void uiUninit(void) +{ + if (!globalPool) + uiprivUserBug("You must call uiInit() first!"); + [globalPool release]; + + @autoreleasepool { + uiprivUninitUnderlineColors(); + [delegate release]; + [uiprivNSApp() setDelegate:nil]; + [app release]; + uiprivUninitAlloc(); + } +} + +void uiFreeInitError(const char *err) +{ +} + +void uiMain(void) +{ + isRunning = ^{ + return [uiprivNSApp() isRunning]; + }; + [uiprivNSApp() run]; +} + +void uiMainSteps(void) +{ + // SDL does this and it seems to be necessary for the menubar to work (see #182) + [uiprivNSApp() finishLaunching]; + isRunning = ^{ + return stepsIsRunning; + }; + stepsIsRunning = YES; +} + +int uiMainStep(int wait) +{ + uiprivNextEventArgs nea; + + nea.mask = NSAnyEventMask; + + // ProPuke did this in his original PR requesting this + // I'm not sure if this will work, but I assume it will... + nea.duration = [NSDate distantPast]; + if (wait) // but this is normal so it will work + nea.duration = [NSDate distantFuture]; + + nea.mode = NSDefaultRunLoopMode; + nea.dequeue = YES; + + return uiprivMainStep(&nea, ^(NSEvent *e) { + return NO; + }); +} + +// see also: +// - http://www.cocoawithlove.com/2009/01/demystifying-nsapplication-by.html +// - https://github.com/gnustep/gui/blob/master/Source/NSApplication.m +int uiprivMainStep(uiprivNextEventArgs *nea, BOOL (^interceptEvent)(NSEvent *e)) +{ + NSDate *expire; + NSEvent *e; + NSEventType type; + + @autoreleasepool { + if (!isRunning()) + return 0; + + e = [uiprivNSApp() nextEventMatchingMask:nea->mask + untilDate:nea->duration + inMode:nea->mode + dequeue:nea->dequeue]; + if (e == nil) + return 1; + + type = [e type]; + if (!interceptEvent(e)) + [uiprivNSApp() sendEvent:e]; + [uiprivNSApp() updateWindows]; + + // GNUstep does this + // it also updates the Services menu but there doesn't seem to be a public API for that so + if (type != NSPeriodic && type != NSMouseMoved) + [[uiprivNSApp() mainMenu] update]; + + return 1; + } +} + +void uiQuit(void) +{ + canQuit = YES; + [uiprivNSApp() terminate:uiprivNSApp()]; +} + +// thanks to mikeash in irc.freenode.net/#macdev for suggesting the use of Grand Central Dispatch for this +// LONGTERM will dispatch_get_main_queue() break after _CFRunLoopSetCurrent()? +void uiQueueMain(void (*f)(void *data), void *data) +{ + // dispatch_get_main_queue() is a serial queue so it will not execute multiple uiQueueMain() functions concurrently + // the signature of f matches dispatch_function_t + dispatch_async_f(dispatch_get_main_queue(), data, f); +} + +@interface uiprivTimerDelegate : NSObject { + int (*f)(void *data); + void *data; +} +- (id)initWithCallback:(int (*)(void *))callback data:(void *)callbackData; +- (void)doTimer:(NSTimer *)timer; +@end + +@implementation uiprivTimerDelegate + +- (id)initWithCallback:(int (*)(void *))callback data:(void *)callbackData +{ + self = [super init]; + if (self) { + self->f = callback; + self->data = callbackData; + } + return self; +} + +- (void)doTimer:(NSTimer *)timer +{ + if (!(*(self->f))(self->data)) + [timer invalidate]; +} + +@end + +void uiTimer(int milliseconds, int (*f)(void *data), void *data) +{ + uiprivTimerDelegate *delegate; + + delegate = [[uiprivTimerDelegate alloc] initWithCallback:f data:data]; + [NSTimer scheduledTimerWithTimeInterval:(milliseconds / 1000.0) + target:delegate + selector:@selector(doTimer:) + userInfo:nil + repeats:YES]; + [delegate release]; +} + +// TODO figure out the best way to clean the above up in uiUninit(), if it's even necessary +// TODO that means figure out if timers can still fire without the main loop diff --git a/dep/libui/darwin/map.m b/dep/libui/darwin/map.m new file mode 100644 index 0000000..a977417 --- /dev/null +++ b/dep/libui/darwin/map.m @@ -0,0 +1,61 @@ +// 17 august 2015 +#import "uipriv_darwin.h" + +// unfortunately NSMutableDictionary copies its keys, meaning we can't use it for pointers +// hence, this file +// we could expose a NSMapTable directly, but let's treat all pointers as opaque and hide the implementation, just to be safe and prevent even more rewrites later +struct uiprivMap { + NSMapTable *m; +}; + +uiprivMap *uiprivNewMap(void) +{ + uiprivMap *m; + + m = uiprivNew(uiprivMap); + m->m = [[NSMapTable alloc] initWithKeyOptions:(NSPointerFunctionsOpaqueMemory | NSPointerFunctionsOpaquePersonality) + valueOptions:(NSPointerFunctionsOpaqueMemory | NSPointerFunctionsOpaquePersonality) + capacity:0]; + return m; +} + +void uiprivMapDestroy(uiprivMap *m) +{ + if ([m->m count] != 0) + uiprivImplBug("attempt to destroy map with items inside"); + [m->m release]; + uiprivFree(m); +} + +void *uiprivMapGet(uiprivMap *m, void *key) +{ + return NSMapGet(m->m, key); +} + +void uiprivMapSet(uiprivMap *m, void *key, void *value) +{ + NSMapInsert(m->m, key, value); +} + +void uiprivMapDelete(uiprivMap *m, void *key) +{ + NSMapRemove(m->m, key); +} + +void uiprivMapWalk(uiprivMap *m, void (*f)(void *key, void *value)) +{ + NSMapEnumerator e; + void *k, *v; + + e = NSEnumerateMapTable(m->m); + k = NULL; + v = NULL; + while (NSNextMapEnumeratorPair(&e, &k, &v)) + f(k, v); + NSEndMapTableEnumeration(&e); +} + +void uiprivMapReset(uiprivMap *m) +{ + NSResetMapTable(m->m); +} diff --git a/dep/libui/darwin/menu.m b/dep/libui/darwin/menu.m new file mode 100644 index 0000000..153255c --- /dev/null +++ b/dep/libui/darwin/menu.m @@ -0,0 +1,368 @@ +// 28 april 2015 +#import "uipriv_darwin.h" + +static NSMutableArray *menus = nil; +static BOOL menusFinalized = NO; + +struct uiMenu { + NSMenu *menu; + NSMenuItem *item; + NSMutableArray *items; +}; + +struct uiMenuItem { + NSMenuItem *item; + int type; + BOOL disabled; + void (*onClicked)(uiMenuItem *, uiWindow *, void *); + void *onClickedData; +}; + +enum { + typeRegular, + typeCheckbox, + typeQuit, + typePreferences, + typeAbout, + typeSeparator, +}; + +static void mapItemReleaser(void *key, void *value) +{ + uiMenuItem *item; + + item = (uiMenuItem *) value; + [item->item release]; +} + +@implementation uiprivMenuManager + +- (id)init +{ + self = [super init]; + if (self) { + self->items = uiprivNewMap(); + self->hasQuit = NO; + self->hasPreferences = NO; + self->hasAbout = NO; + } + return self; +} + +- (void)dealloc +{ + uiprivMapWalk(self->items, mapItemReleaser); + uiprivMapReset(self->items); + uiprivMapDestroy(self->items); + uiprivUninitMenus(); + [super dealloc]; +} + +- (IBAction)onClicked:(id)sender +{ + uiMenuItem *item; + + item = (uiMenuItem *) uiprivMapGet(self->items, sender); + if (item->type == typeCheckbox) + uiMenuItemSetChecked(item, !uiMenuItemChecked(item)); + // use the key window as the source of the menu event; it's the active window + (*(item->onClicked))(item, uiprivWindowFromNSWindow([uiprivNSApp() keyWindow]), item->onClickedData); +} + +- (IBAction)onQuitClicked:(id)sender +{ + if (uiprivShouldQuit()) + uiQuit(); +} + +- (void)register:(NSMenuItem *)item to:(uiMenuItem *)smi +{ + switch (smi->type) { + case typeQuit: + if (self->hasQuit) + uiprivUserBug("You can't have multiple Quit menu items in one program."); + self->hasQuit = YES; + break; + case typePreferences: + if (self->hasPreferences) + uiprivUserBug("You can't have multiple Preferences menu items in one program."); + self->hasPreferences = YES; + break; + case typeAbout: + if (self->hasAbout) + uiprivUserBug("You can't have multiple About menu items in one program."); + self->hasAbout = YES; + break; + } + uiprivMapSet(self->items, item, smi); +} + +// on OS X there are two ways to handle menu items being enabled or disabled: automatically and manually +// unfortunately, the application menu requires automatic menu handling for the Hide, Hide Others, and Show All items to work correctly +// therefore, we have to handle enabling of the other options ourselves +- (BOOL)validateMenuItem:(NSMenuItem *)item +{ + uiMenuItem *smi; + + // disable the special items if they aren't present + if (item == self.quitItem && !self->hasQuit) + return NO; + if (item == self.preferencesItem && !self->hasPreferences) + return NO; + if (item == self.aboutItem && !self->hasAbout) + return NO; + // then poll the item's enabled/disabled state + smi = (uiMenuItem *) uiprivMapGet(self->items, item); + return !smi->disabled; +} + +// Cocoa constructs the default application menu by hand for each program; that's what MainMenu.[nx]ib does +- (void)buildApplicationMenu:(NSMenu *)menubar +{ + NSString *appName; + NSMenuItem *appMenuItem; + NSMenu *appMenu; + NSMenuItem *item; + NSString *title; + NSMenu *servicesMenu; + + // note: no need to call setAppleMenu: on this anymore; see https://developer.apple.com/library/mac/releasenotes/AppKit/RN-AppKitOlderNotes/#X10_6Notes + appName = [[NSProcessInfo processInfo] processName]; + appMenuItem = [[[NSMenuItem alloc] initWithTitle:appName action:NULL keyEquivalent:@""] autorelease]; + appMenu = [[[NSMenu alloc] initWithTitle:appName] autorelease]; + [appMenuItem setSubmenu:appMenu]; + [menubar addItem:appMenuItem]; + + // first is About + title = [@"About " stringByAppendingString:appName]; + item = [[[NSMenuItem alloc] initWithTitle:title action:@selector(onClicked:) keyEquivalent:@""] autorelease]; + [item setTarget:self]; + [appMenu addItem:item]; + self.aboutItem = item; + + [appMenu addItem:[NSMenuItem separatorItem]]; + + // next is Preferences + item = [[[NSMenuItem alloc] initWithTitle:@"Preferences…" action:@selector(onClicked:) keyEquivalent:@","] autorelease]; + [item setTarget:self]; + [appMenu addItem:item]; + self.preferencesItem = item; + + [appMenu addItem:[NSMenuItem separatorItem]]; + + // next is Services + item = [[[NSMenuItem alloc] initWithTitle:@"Services" action:NULL keyEquivalent:@""] autorelease]; + servicesMenu = [[[NSMenu alloc] initWithTitle:@"Services"] autorelease]; + [item setSubmenu:servicesMenu]; + [uiprivNSApp() setServicesMenu:servicesMenu]; + [appMenu addItem:item]; + + [appMenu addItem:[NSMenuItem separatorItem]]; + + // next are the three hiding options + title = [@"Hide " stringByAppendingString:appName]; + item = [[[NSMenuItem alloc] initWithTitle:title action:@selector(hide:) keyEquivalent:@"h"] autorelease]; + // the .xib file says they go to -1 ("First Responder", which sounds wrong...) + // to do that, we simply leave the target as nil + [appMenu addItem:item]; + item = [[[NSMenuItem alloc] initWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"] autorelease]; + [item setKeyEquivalentModifierMask:(NSAlternateKeyMask | NSCommandKeyMask)]; + [appMenu addItem:item]; + item = [[[NSMenuItem alloc] initWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""] autorelease]; + [appMenu addItem:item]; + + [appMenu addItem:[NSMenuItem separatorItem]]; + + // and finally Quit + // DON'T use @selector(terminate:) as the action; we handle termination ourselves + title = [@"Quit " stringByAppendingString:appName]; + item = [[[NSMenuItem alloc] initWithTitle:title action:@selector(onQuitClicked:) keyEquivalent:@"q"] autorelease]; + [item setTarget:self]; + [appMenu addItem:item]; + self.quitItem = item; +} + +- (NSMenu *)makeMenubar +{ + NSMenu *menubar; + + menubar = [[[NSMenu alloc] initWithTitle:@""] autorelease]; + [self buildApplicationMenu:menubar]; + return menubar; +} + +@end + +static void defaultOnClicked(uiMenuItem *item, uiWindow *w, void *data) +{ + // do nothing +} + +void uiMenuItemEnable(uiMenuItem *item) +{ + item->disabled = NO; + // we don't need to explicitly update the menus here; they'll be updated the next time they're opened (thanks mikeash in irc.freenode.net/#macdev) +} + +void uiMenuItemDisable(uiMenuItem *item) +{ + item->disabled = YES; +} + +void uiMenuItemOnClicked(uiMenuItem *item, void (*f)(uiMenuItem *, uiWindow *, void *), void *data) +{ + if (item->type == typeQuit) + uiprivUserBug("You can't call uiMenuItemOnClicked() on a Quit item; use uiOnShouldQuit() instead."); + item->onClicked = f; + item->onClickedData = data; +} + +int uiMenuItemChecked(uiMenuItem *item) +{ + return [item->item state] != NSOffState; +} + +void uiMenuItemSetChecked(uiMenuItem *item, int checked) +{ + NSInteger state; + + state = NSOffState; + if ([item->item state] == NSOffState) + state = NSOnState; + [item->item setState:state]; +} + +static uiMenuItem *newItem(uiMenu *m, int type, const char *name) +{ + @autoreleasepool { + + uiMenuItem *item; + + if (menusFinalized) + uiprivUserBug("You can't create a new menu item after menus have been finalized."); + + item = uiprivNew(uiMenuItem); + + item->type = type; + switch (item->type) { + case typeQuit: + item->item = [uiprivAppDelegate().menuManager.quitItem retain]; + break; + case typePreferences: + item->item = [uiprivAppDelegate().menuManager.preferencesItem retain]; + break; + case typeAbout: + item->item = [uiprivAppDelegate().menuManager.aboutItem retain]; + break; + case typeSeparator: + item->item = [[NSMenuItem separatorItem] retain]; + [m->menu addItem:item->item]; + break; + default: + item->item = [[NSMenuItem alloc] initWithTitle:uiprivToNSString(name) action:@selector(onClicked:) keyEquivalent:@""]; + [item->item setTarget:uiprivAppDelegate().menuManager]; + [m->menu addItem:item->item]; + break; + } + + [uiprivAppDelegate().menuManager register:item->item to:item]; + item->onClicked = defaultOnClicked; + + [m->items addObject:[NSValue valueWithPointer:item]]; + + return item; + + } // @autoreleasepool +} + +uiMenuItem *uiMenuAppendItem(uiMenu *m, const char *name) +{ + return newItem(m, typeRegular, name); +} + +uiMenuItem *uiMenuAppendCheckItem(uiMenu *m, const char *name) +{ + return newItem(m, typeCheckbox, name); +} + +uiMenuItem *uiMenuAppendQuitItem(uiMenu *m) +{ + // duplicate check is in the register:to: selector + return newItem(m, typeQuit, NULL); +} + +uiMenuItem *uiMenuAppendPreferencesItem(uiMenu *m) +{ + // duplicate check is in the register:to: selector + return newItem(m, typePreferences, NULL); +} + +uiMenuItem *uiMenuAppendAboutItem(uiMenu *m) +{ + // duplicate check is in the register:to: selector + return newItem(m, typeAbout, NULL); +} + +void uiMenuAppendSeparator(uiMenu *m) +{ + newItem(m, typeSeparator, NULL); +} + +uiMenu *uiNewMenu(const char *name) +{ + @autoreleasepool { + + uiMenu *m; + + if (menusFinalized) + uiprivUserBug("You can't create a new menu after menus have been finalized."); + if (menus == nil) + menus = [NSMutableArray new]; + + m = uiprivNew(uiMenu); + + m->menu = [[NSMenu alloc] initWithTitle:uiprivToNSString(name)]; + // use automatic menu item enabling for all menus for consistency's sake + + m->item = [[NSMenuItem alloc] initWithTitle:uiprivToNSString(name) action:NULL keyEquivalent:@""]; + [m->item setSubmenu:m->menu]; + + m->items = [NSMutableArray new]; + + [[uiprivNSApp() mainMenu] addItem:m->item]; + + [menus addObject:[NSValue valueWithPointer:m]]; + + return m; + + } // @autoreleasepool +} + +void uiprivFinalizeMenus(void) +{ + menusFinalized = YES; +} + +void uiprivUninitMenus(void) +{ + if (menus == NULL) + return; + [menus enumerateObjectsUsingBlock:^(id obj, NSUInteger index, BOOL *stop) { + NSValue *v; + uiMenu *m; + + v = (NSValue *) obj; + m = (uiMenu *) [v pointerValue]; + [m->items enumerateObjectsUsingBlock:^(id obj, NSUInteger index, BOOL *stop) { + NSValue *v; + uiMenuItem *mi; + + v = (NSValue *) obj; + mi = (uiMenuItem *) [v pointerValue]; + uiprivFree(mi); + }]; + [m->items release]; + uiprivFree(m); + }]; + [menus release]; +} diff --git a/dep/libui/darwin/meson.build b/dep/libui/darwin/meson.build new file mode 100644 index 0000000..c251046 --- /dev/null +++ b/dep/libui/darwin/meson.build @@ -0,0 +1,64 @@ +# 23 march 2019 + +libui_sources += [ + 'darwin/aat.m', + 'darwin/alloc.m', + 'darwin/area.m', + 'darwin/areaevents.m', + 'darwin/attrstr.m', + 'darwin/autolayout.m', + 'darwin/box.m', + 'darwin/button.m', + 'darwin/checkbox.m', + 'darwin/colorbutton.m', + 'darwin/combobox.m', + 'darwin/control.m', + 'darwin/datetimepicker.m', + 'darwin/debug.m', + 'darwin/draw.m', + 'darwin/drawtext.m', + 'darwin/editablecombo.m', + 'darwin/entry.m', + 'darwin/fontbutton.m', + 'darwin/fontmatch.m', + 'darwin/fonttraits.m', + 'darwin/fontvariation.m', + 'darwin/form.m', + 'darwin/future.m', + 'darwin/graphemes.m', + 'darwin/grid.m', + 'darwin/group.m', + 'darwin/image.m', + 'darwin/label.m', + 'darwin/main.m', + 'darwin/map.m', + 'darwin/menu.m', + 'darwin/multilineentry.m', + 'darwin/opentype.m', + 'darwin/progressbar.m', + 'darwin/radiobuttons.m', + 'darwin/scrollview.m', + 'darwin/separator.m', + 'darwin/slider.m', + 'darwin/spinbox.m', + 'darwin/stddialogs.m', + 'darwin/tab.m', + 'darwin/table.m', + 'darwin/tablecolumn.m', + 'darwin/text.m', + 'darwin/undocumented.m', + 'darwin/util.m', + 'darwin/window.m', + 'darwin/winmoveresize.m', +] + +libui_deps += [ + meson.get_compiler('objc').find_library('objc', + required: true), + dependency('appleframeworks', + modules: ['Foundation', 'AppKit'], + required: true), +] +libui_soversion = 'A' +# the / is required by some older versions of OS X +libui_rpath = '@executable_path/' diff --git a/dep/libui/darwin/multilineentry.m b/dep/libui/darwin/multilineentry.m new file mode 100644 index 0000000..d57284a --- /dev/null +++ b/dep/libui/darwin/multilineentry.m @@ -0,0 +1,233 @@ +// 8 december 2015 +#import "uipriv_darwin.h" + +// NSTextView has no intrinsic content size by default, which wreaks havoc on a pure-Auto Layout system +// we'll have to take over to get it to work +// see also http://stackoverflow.com/questions/24210153/nstextview-not-properly-resizing-with-auto-layout and http://stackoverflow.com/questions/11237622/using-autolayout-with-expanding-nstextviews +@interface intrinsicSizeTextView : NSTextView { + uiMultilineEntry *libui_e; +} +- (id)initWithFrame:(NSRect)r e:(uiMultilineEntry *)e; +@end + +struct uiMultilineEntry { + uiDarwinControl c; + NSScrollView *sv; + intrinsicSizeTextView *tv; + uiprivScrollViewData *d; + void (*onChanged)(uiMultilineEntry *, void *); + void *onChangedData; + BOOL changing; +}; + +@implementation intrinsicSizeTextView + +- (id)initWithFrame:(NSRect)r e:(uiMultilineEntry *)e +{ + self = [super initWithFrame:r]; + if (self) + self->libui_e = e; + return self; +} + +- (NSSize)intrinsicContentSize +{ + NSTextContainer *textContainer; + NSLayoutManager *layoutManager; + NSRect rect; + + textContainer = [self textContainer]; + layoutManager = [self layoutManager]; + [layoutManager ensureLayoutForTextContainer:textContainer]; + rect = [layoutManager usedRectForTextContainer:textContainer]; + return rect.size; +} + +- (void)didChangeText +{ + [super didChangeText]; + [self invalidateIntrinsicContentSize]; + if (!self->libui_e->changing) + (*(self->libui_e->onChanged))(self->libui_e, self->libui_e->onChangedData); +} + +@end + +uiDarwinControlAllDefaultsExceptDestroy(uiMultilineEntry, sv) + +static void uiMultilineEntryDestroy(uiControl *c) +{ + uiMultilineEntry *e = uiMultilineEntry(c); + + uiprivScrollViewFreeData(e->sv, e->d); + [e->tv release]; + [e->sv release]; + uiFreeControl(uiControl(e)); +} + +static void defaultOnChanged(uiMultilineEntry *e, void *data) +{ + // do nothing +} + +char *uiMultilineEntryText(uiMultilineEntry *e) +{ + return uiDarwinNSStringToText([e->tv string]); +} + +void uiMultilineEntrySetText(uiMultilineEntry *e, const char *text) +{ + [[e->tv textStorage] replaceCharactersInRange:NSMakeRange(0, [[e->tv string] length]) + withString:uiprivToNSString(text)]; + // must be called explicitly according to the documentation of shouldChangeTextInRange:replacementString: + e->changing = YES; + [e->tv didChangeText]; + e->changing = NO; +} + +// TODO scroll to end? +void uiMultilineEntryAppend(uiMultilineEntry *e, const char *text) +{ + [[e->tv textStorage] replaceCharactersInRange:NSMakeRange([[e->tv string] length], 0) + withString:uiprivToNSString(text)]; + e->changing = YES; + [e->tv didChangeText]; + e->changing = NO; +} + +void uiMultilineEntryOnChanged(uiMultilineEntry *e, void (*f)(uiMultilineEntry *e, void *data), void *data) +{ + e->onChanged = f; + e->onChangedData = data; +} + +int uiMultilineEntryReadOnly(uiMultilineEntry *e) +{ + return [e->tv isEditable] == NO; +} + +void uiMultilineEntrySetReadOnly(uiMultilineEntry *e, int readonly) +{ + BOOL editable; + + editable = YES; + if (readonly) + editable = NO; + [e->tv setEditable:editable]; +} + +static uiMultilineEntry *finishMultilineEntry(BOOL hscroll) +{ + uiMultilineEntry *e; + NSFont *font; + uiprivScrollViewCreateParams p; + + uiDarwinNewControl(uiMultilineEntry, e); + + e->tv = [[intrinsicSizeTextView alloc] initWithFrame:NSZeroRect e:e]; + + // verified against Interface Builder for a sufficiently customized text view + + // NSText properties: + // this is what Interface Builder sets the background color to + [e->tv setBackgroundColor:[NSColor colorWithCalibratedWhite:1.0 alpha:1.0]]; + [e->tv setDrawsBackground:YES]; + [e->tv setEditable:YES]; + [e->tv setSelectable:YES]; + [e->tv setFieldEditor:NO]; + [e->tv setRichText:NO]; + [e->tv setImportsGraphics:NO]; + [e->tv setUsesFontPanel:NO]; + [e->tv setRulerVisible:NO]; + // we'll handle font last + // while setAlignment: has been around since 10.0, the named constant "NSTextAlignmentNatural" seems to have only been introduced in 10.11 +#define ourNSTextAlignmentNatural 4 + [e->tv setAlignment:ourNSTextAlignmentNatural]; + // textColor is set to nil, just keep the dfault + [e->tv setBaseWritingDirection:NSWritingDirectionNatural]; + [e->tv setHorizontallyResizable:NO]; + [e->tv setVerticallyResizable:YES]; + + // NSTextView properties: + [e->tv setAllowsDocumentBackgroundColorChange:NO]; + [e->tv setAllowsUndo:YES]; + // default paragraph style is nil; keep default + [e->tv setAllowsImageEditing:NO]; + [e->tv setAutomaticQuoteSubstitutionEnabled:NO]; + [e->tv setAutomaticLinkDetectionEnabled:NO]; + [e->tv setDisplaysLinkToolTips:YES]; + [e->tv setUsesRuler:NO]; + [e->tv setUsesInspectorBar:NO]; + [e->tv setSelectionGranularity:NSSelectByCharacter]; + // there is a dedicated named insertion point color but oh well + [e->tv setInsertionPointColor:[NSColor controlTextColor]]; + // typing attributes is nil; keep default (we change it below for fonts though) + [e->tv setSmartInsertDeleteEnabled:NO]; + [e->tv setContinuousSpellCheckingEnabled:NO]; + [e->tv setGrammarCheckingEnabled:NO]; + [e->tv setUsesFindPanel:YES]; + [e->tv setEnabledTextCheckingTypes:0]; + [e->tv setAutomaticDashSubstitutionEnabled:NO]; + [e->tv setAutomaticDataDetectionEnabled:NO]; + [e->tv setAutomaticSpellingCorrectionEnabled:NO]; + [e->tv setAutomaticTextReplacementEnabled:NO]; + [e->tv setUsesFindBar:NO]; + [e->tv setIncrementalSearchingEnabled:NO]; + + // NSTextContainer properties: + [[e->tv textContainer] setWidthTracksTextView:YES]; + [[e->tv textContainer] setHeightTracksTextView:NO]; + + // NSLayoutManager properties: + [[e->tv layoutManager] setAllowsNonContiguousLayout:YES]; + + // now just to be safe; this will do some of the above but whatever + uiprivDisableAutocorrect(e->tv); + + // see https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/TextUILayer/Tasks/TextInScrollView.html + // notice we don't use the Auto Layout code; see scrollview.m for more details + [e->tv setMaxSize:NSMakeSize(CGFLOAT_MAX, CGFLOAT_MAX)]; + [e->tv setVerticallyResizable:YES]; + [e->tv setHorizontallyResizable:hscroll]; + if (hscroll) { + [e->tv setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)]; + [[e->tv textContainer] setWidthTracksTextView:NO]; + } else { + [e->tv setAutoresizingMask:NSViewWidthSizable]; + [[e->tv textContainer] setWidthTracksTextView:YES]; + } + [[e->tv textContainer] setContainerSize:NSMakeSize(CGFLOAT_MAX, CGFLOAT_MAX)]; + + // don't use uiDarwinSetControlFont() directly; we have to do a little extra work to set the font + font = [NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:NSRegularControlSize]]; + [e->tv setTypingAttributes:[NSDictionary + dictionaryWithObject:font + forKey:NSFontAttributeName]]; + // e->tv font from Interface Builder is nil, but setFont:nil throws an exception + // let's just set it to the standard control font anyway, just to be safe + [e->tv setFont:font]; + + memset(&p, 0, sizeof (uiprivScrollViewCreateParams)); + p.DocumentView = e->tv; + // this is what Interface Builder sets it to + p.BackgroundColor = [NSColor colorWithCalibratedWhite:1.0 alpha:1.0]; + p.DrawsBackground = YES; + p.Bordered = YES; + p.HScroll = hscroll; + p.VScroll = YES; + e->sv = uiprivMkScrollView(&p, &(e->d)); + + uiMultilineEntryOnChanged(e, defaultOnChanged, NULL); + + return e; +} + +uiMultilineEntry *uiNewMultilineEntry(void) +{ + return finishMultilineEntry(NO); +} + +uiMultilineEntry *uiNewNonWrappingMultilineEntry(void) +{ + return finishMultilineEntry(YES); +} diff --git a/dep/libui/darwin/opentype.m b/dep/libui/darwin/opentype.m new file mode 100644 index 0000000..be12917 --- /dev/null +++ b/dep/libui/darwin/opentype.m @@ -0,0 +1,113 @@ +// 11 may 2017 +#import "uipriv_darwin.h" +#import "attrstr.h" + +struct addCTFeatureEntryParams { + CFMutableArrayRef array; + const void *tagKey; + BOOL tagIsNumber; + CFNumberType tagType; + const void *tagValue; + const void *valueKey; + CFNumberType valueType; + const void *valueValue; +}; + +static void addCTFeatureEntry(struct addCTFeatureEntryParams *p) +{ + CFDictionaryRef featureDict; + CFNumberRef tagNum, valueNum; + const void *keys[2], *values[2]; + + keys[0] = p->tagKey; + tagNum = NULL; + values[0] = p->tagValue; + if (p->tagIsNumber) { + tagNum = CFNumberCreate(NULL, p->tagType, p->tagValue); + values[0] = tagNum; + } + + keys[1] = p->valueKey; + valueNum = CFNumberCreate(NULL, p->valueType, p->valueValue); + values[1] = valueNum; + + featureDict = CFDictionaryCreate(NULL, + keys, values, 2, + // TODO are these correct? + &kCFCopyStringDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + if (featureDict == NULL) { + // TODO + } + CFArrayAppendValue(p->array, featureDict); + + CFRelease(featureDict); + CFRelease(valueNum); + if (p->tagIsNumber) + CFRelease(tagNum); +} + +static uiForEach otfArrayForEachAAT(const uiOpenTypeFeatures *otf, char a, char b, char c, char d, uint32_t value, void *data) +{ + __block struct addCTFeatureEntryParams p; + + p.array = (CFMutableArrayRef) data; + p.tagIsNumber = YES; + uiprivOpenTypeToAAT(a, b, c, d, value, ^(uint16_t type, uint16_t selector) { + p.tagKey = kCTFontFeatureTypeIdentifierKey; + p.tagType = kCFNumberSInt16Type; + p.tagValue = (const SInt16 *) (&type); + p.valueKey = kCTFontFeatureSelectorIdentifierKey; + p.valueType = kCFNumberSInt16Type; + p.valueValue = (const SInt16 *) (&selector); + addCTFeatureEntry(&p); + }); + return uiForEachContinue; +} + +// TODO find out which fonts differ in AAT small caps and test them with this +static uiForEach otfArrayForEachOT(const uiOpenTypeFeatures *otf, char a, char b, char c, char d, uint32_t value, void *data) +{ + struct addCTFeatureEntryParams p; + char tagcstr[5]; + CFStringRef tagstr; + + p.array = (CFMutableArrayRef) data; + + p.tagKey = *uiprivFUTURE_kCTFontOpenTypeFeatureTag; + p.tagIsNumber = NO; + tagcstr[0] = a; + tagcstr[1] = b; + tagcstr[2] = c; + tagcstr[3] = d; + tagcstr[4] = '\0'; + tagstr = CFStringCreateWithCString(NULL, tagcstr, kCFStringEncodingUTF8); + if (tagstr == NULL) { + // TODO + } + p.tagValue = tagstr; + + p.valueKey = *uiprivFUTURE_kCTFontOpenTypeFeatureValue; + p.valueType = kCFNumberSInt32Type; + p.valueValue = (const SInt32 *) (&value); + addCTFeatureEntry(&p); + + CFRelease(tagstr); + return uiForEachContinue; +} + +CFArrayRef uiprivOpenTypeFeaturesToCTFeatures(const uiOpenTypeFeatures *otf) +{ + CFMutableArrayRef array; + uiOpenTypeFeaturesForEachFunc f; + + array = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); + if (array == NULL) { + // TODO + } + f = otfArrayForEachAAT; + if (uiprivFUTURE_kCTFontOpenTypeFeatureTag != NULL && uiprivFUTURE_kCTFontOpenTypeFeatureValue != NULL) + f = otfArrayForEachOT; + uiOpenTypeFeaturesForEach(otf, f, array); + return array; +} diff --git a/dep/libui/darwin/progressbar.m b/dep/libui/darwin/progressbar.m new file mode 100644 index 0000000..1f5390f --- /dev/null +++ b/dep/libui/darwin/progressbar.m @@ -0,0 +1,78 @@ +// 14 august 2015 +#import "uipriv_darwin.h" + +// NSProgressIndicator has no intrinsic width by default; use the default width in Interface Builder +#define progressIndicatorWidth 100 + +@interface intrinsicWidthNSProgressIndicator : NSProgressIndicator +@end + +@implementation intrinsicWidthNSProgressIndicator + +- (NSSize)intrinsicContentSize +{ + NSSize s; + + s = [super intrinsicContentSize]; + s.width = progressIndicatorWidth; + return s; +} + +@end + +struct uiProgressBar { + uiDarwinControl c; + NSProgressIndicator *pi; +}; + +uiDarwinControlAllDefaults(uiProgressBar, pi) + +int uiProgressBarValue(uiProgressBar *p) +{ + if ([p->pi isIndeterminate]) + return -1; + return [p->pi doubleValue]; +} + +void uiProgressBarSetValue(uiProgressBar *p, int value) +{ + if (value == -1) { + [p->pi setIndeterminate:YES]; + [p->pi startAnimation:p->pi]; + return; + } + + if ([p->pi isIndeterminate]) { + [p->pi setIndeterminate:NO]; + [p->pi stopAnimation:p->pi]; + } + + if (value < 0 || value > 100) + uiprivUserBug("Value %d out of range for a uiProgressBar.", value); + + // on 10.8 there's an animation when the progress bar increases, just like with Aero + if (value == 100) { + [p->pi setMaxValue:101]; + [p->pi setDoubleValue:101]; + [p->pi setDoubleValue:100]; + [p->pi setMaxValue:100]; + return; + } + [p->pi setDoubleValue:((double) (value + 1))]; + [p->pi setDoubleValue:((double) value)]; +} + +uiProgressBar *uiNewProgressBar(void) +{ + uiProgressBar *p; + + uiDarwinNewControl(uiProgressBar, p); + + p->pi = [[intrinsicWidthNSProgressIndicator alloc] initWithFrame:NSZeroRect]; + [p->pi setControlSize:NSRegularControlSize]; + [p->pi setBezeled:YES]; + [p->pi setStyle:NSProgressIndicatorBarStyle]; + [p->pi setIndeterminate:NO]; + + return p; +} diff --git a/dep/libui/darwin/radiobuttons.m b/dep/libui/darwin/radiobuttons.m new file mode 100644 index 0000000..c7b0371 --- /dev/null +++ b/dep/libui/darwin/radiobuttons.m @@ -0,0 +1,207 @@ +// 14 august 2015 +#import "uipriv_darwin.h" + +// TODO resizing the controlgallery vertically causes the third button to still resize :| + +// In the old days you would use a NSMatrix for this; as of OS X 10.8 this was deprecated and now you need just a bunch of NSButtons with the same superview AND same action method. +// This is documented on the NSMatrix page, but the rest of the OS X documentation says to still use NSMatrix. +// NSMatrix has weird quirks anyway... + +// LONGTERM 6 units of spacing between buttons, as suggested by Interface Builder? + +@interface radioButtonsDelegate : NSObject { + uiRadioButtons *libui_r; +} +- (id)initWithR:(uiRadioButtons *)r; +- (IBAction)onClicked:(id)sender; +@end + +struct uiRadioButtons { + uiDarwinControl c; + NSView *view; + NSMutableArray *buttons; + NSMutableArray *constraints; + NSLayoutConstraint *lastv; + radioButtonsDelegate *delegate; + void (*onSelected)(uiRadioButtons *, void *); + void *onSelectedData; +}; + +@implementation radioButtonsDelegate + +- (id)initWithR:(uiRadioButtons *)r +{ + self = [super init]; + if (self) + self->libui_r = r; + return self; +} + +- (IBAction)onClicked:(id)sender +{ + uiRadioButtons *r = self->libui_r; + + (*(r->onSelected))(r, r->onSelectedData); +} + +@end + +uiDarwinControlAllDefaultsExceptDestroy(uiRadioButtons, view) + +static void defaultOnSelected(uiRadioButtons *r, void *data) +{ + // do nothing +} + +static void uiRadioButtonsDestroy(uiControl *c) +{ + uiRadioButtons *r = uiRadioButtons(c); + NSButton *b; + + // drop the constraints + [r->view removeConstraints:r->constraints]; + [r->constraints release]; + if (r->lastv != nil) + [r->lastv release]; + // destroy the buttons + for (b in r->buttons) { + [b setTarget:nil]; + [b removeFromSuperview]; + } + [r->buttons release]; + // destroy the delegate + [r->delegate release]; + // and destroy ourselves + [r->view release]; + uiFreeControl(uiControl(r)); +} + +static NSButton *buttonAt(uiRadioButtons *r, int n) +{ + return (NSButton *) [r->buttons objectAtIndex:n]; +} + +void uiRadioButtonsAppend(uiRadioButtons *r, const char *text) +{ + NSButton *b, *b2; + NSLayoutConstraint *constraint; + + b = [[NSButton alloc] initWithFrame:NSZeroRect]; + [b setTitle:uiprivToNSString(text)]; + [b setButtonType:NSRadioButton]; + // doesn't seem to have an associated bezel style + [b setBordered:NO]; + [b setTransparent:NO]; + uiDarwinSetControlFont(b, NSRegularControlSize); + [b setTranslatesAutoresizingMaskIntoConstraints:NO]; + + [b setTarget:r->delegate]; + [b setAction:@selector(onClicked:)]; + + [r->buttons addObject:b]; + [r->view addSubview:b]; + + // pin horizontally to the edges of the superview + constraint = uiprivMkConstraint(b, NSLayoutAttributeLeading, + NSLayoutRelationEqual, + r->view, NSLayoutAttributeLeading, + 1, 0, + @"uiRadioButtons button leading constraint"); + [r->view addConstraint:constraint]; + [r->constraints addObject:constraint]; + constraint = uiprivMkConstraint(b, NSLayoutAttributeTrailing, + NSLayoutRelationEqual, + r->view, NSLayoutAttributeTrailing, + 1, 0, + @"uiRadioButtons button trailing constraint"); + [r->view addConstraint:constraint]; + [r->constraints addObject:constraint]; + + // if this is the first view, pin it to the top + // otherwise pin to the bottom of the last + if ([r->buttons count] == 1) + constraint = uiprivMkConstraint(b, NSLayoutAttributeTop, + NSLayoutRelationEqual, + r->view, NSLayoutAttributeTop, + 1, 0, + @"uiRadioButtons first button top constraint"); + else { + b2 = buttonAt(r, [r->buttons count] - 2); + constraint = uiprivMkConstraint(b, NSLayoutAttributeTop, + NSLayoutRelationEqual, + b2, NSLayoutAttributeBottom, + 1, 0, + @"uiRadioButtons non-first button top constraint"); + } + [r->view addConstraint:constraint]; + [r->constraints addObject:constraint]; + + // if there is a previous bottom constraint, remove it + if (r->lastv != nil) { + [r->view removeConstraint:r->lastv]; + [r->constraints removeObject:r->lastv]; + [r->lastv release]; + } + + // and make the new bottom constraint + r->lastv = uiprivMkConstraint(b, NSLayoutAttributeBottom, + NSLayoutRelationEqual, + r->view, NSLayoutAttributeBottom, + 1, 0, + @"uiRadioButtons last button bottom constraint"); + [r->view addConstraint:r->lastv]; + [r->constraints addObject:r->lastv]; + [r->lastv retain]; +} + +int uiRadioButtonsSelected(uiRadioButtons *r) +{ + NSButton *b; + NSUInteger i; + + for (i = 0; i < [r->buttons count]; i++) { + b = (NSButton *) [r->buttons objectAtIndex:i]; + if ([b state] == NSOnState) + return i; + } + return -1; +} + +void uiRadioButtonsSetSelected(uiRadioButtons *r, int n) +{ + NSButton *b; + NSInteger state; + + state = NSOnState; + if (n == -1) { + n = uiRadioButtonsSelected(r); + if (n == -1) // from nothing to nothing; do nothing + return; + state = NSOffState; + } + b = (NSButton *) [r->buttons objectAtIndex:n]; + [b setState:state]; +} + +void uiRadioButtonsOnSelected(uiRadioButtons *r, void (*f)(uiRadioButtons *, void *), void *data) +{ + r->onSelected = f; + r->onSelectedData = data; +} + +uiRadioButtons *uiNewRadioButtons(void) +{ + uiRadioButtons *r; + + uiDarwinNewControl(uiRadioButtons, r); + + r->view = [[NSView alloc] initWithFrame:NSZeroRect]; + r->buttons = [NSMutableArray new]; + r->constraints = [NSMutableArray new]; + + r->delegate = [[radioButtonsDelegate alloc] initWithR:r]; + + uiRadioButtonsOnSelected(r, defaultOnSelected, NULL); + + return r; +} diff --git a/dep/libui/darwin/scrollview.m b/dep/libui/darwin/scrollview.m new file mode 100644 index 0000000..1b5cc8d --- /dev/null +++ b/dep/libui/darwin/scrollview.m @@ -0,0 +1,61 @@ +// 27 may 2016 +#include "uipriv_darwin.h" + +// see http://stackoverflow.com/questions/37979445/how-do-i-properly-set-up-a-scrolling-nstableview-using-auto-layout-what-ive-tr for why we don't use auto layout +// TODO do the same with uiGroup and uiTab? + +struct uiprivScrollViewData { + BOOL hscroll; + BOOL vscroll; +}; + +NSScrollView *uiprivMkScrollView(uiprivScrollViewCreateParams *p, uiprivScrollViewData **dout) +{ + NSScrollView *sv; + NSBorderType border; + uiprivScrollViewData *d; + + sv = [[NSScrollView alloc] initWithFrame:NSZeroRect]; + if (p->BackgroundColor != nil) + [sv setBackgroundColor:p->BackgroundColor]; + [sv setDrawsBackground:p->DrawsBackground]; + border = NSNoBorder; + if (p->Bordered) + border = NSBezelBorder; + // document view seems to set the cursor properly + [sv setBorderType:border]; + [sv setAutohidesScrollers:YES]; + [sv setHasHorizontalRuler:NO]; + [sv setHasVerticalRuler:NO]; + [sv setRulersVisible:NO]; + [sv setScrollerKnobStyle:NSScrollerKnobStyleDefault]; + // the scroller style is documented as being set by default for us + // LONGTERM verify line and page for programmatically created NSTableView + [sv setScrollsDynamically:YES]; + [sv setFindBarPosition:NSScrollViewFindBarPositionAboveContent]; + [sv setUsesPredominantAxisScrolling:NO]; + [sv setHorizontalScrollElasticity:NSScrollElasticityAutomatic]; + [sv setVerticalScrollElasticity:NSScrollElasticityAutomatic]; + [sv setAllowsMagnification:NO]; + + [sv setDocumentView:p->DocumentView]; + d = uiprivNew(uiprivScrollViewData); + uiprivScrollViewSetScrolling(sv, d, p->HScroll, p->VScroll); + + *dout = d; + return sv; +} + +// based on http://blog.bjhomer.com/2014/08/nsscrollview-and-autolayout.html because (as pointed out there) Apple's official guide is really only for iOS +void uiprivScrollViewSetScrolling(NSScrollView *sv, uiprivScrollViewData *d, BOOL hscroll, BOOL vscroll) +{ + d->hscroll = hscroll; + [sv setHasHorizontalScroller:d->hscroll]; + d->vscroll = vscroll; + [sv setHasVerticalScroller:d->vscroll]; +} + +void uiprivScrollViewFreeData(NSScrollView *sv, uiprivScrollViewData *d) +{ + uiprivFree(d); +} diff --git a/dep/libui/darwin/separator.m b/dep/libui/darwin/separator.m new file mode 100644 index 0000000..a37a376 --- /dev/null +++ b/dep/libui/darwin/separator.m @@ -0,0 +1,45 @@ +// 14 august 2015 +#import "uipriv_darwin.h" + +// TODO make this intrinsic +#define separatorWidth 96 +#define separatorHeight 96 + +struct uiSeparator { + uiDarwinControl c; + NSBox *box; +}; + +uiDarwinControlAllDefaults(uiSeparator, box) + +uiSeparator *uiNewHorizontalSeparator(void) +{ + uiSeparator *s; + + uiDarwinNewControl(uiSeparator, s); + + // make the initial width >= initial height to force horizontal + s->box = [[NSBox alloc] initWithFrame:NSMakeRect(0, 0, 100, 1)]; + [s->box setBoxType:NSBoxSeparator]; + [s->box setBorderType:NSGrooveBorder]; + [s->box setTransparent:NO]; + [s->box setTitlePosition:NSNoTitle]; + + return s; +} + +uiSeparator *uiNewVerticalSeparator(void) +{ + uiSeparator *s; + + uiDarwinNewControl(uiSeparator, s); + + // make the initial height >= initial width to force vertical + s->box = [[NSBox alloc] initWithFrame:NSMakeRect(0, 0, 1, 100)]; + [s->box setBoxType:NSBoxSeparator]; + [s->box setBorderType:NSGrooveBorder]; + [s->box setTransparent:NO]; + [s->box setTitlePosition:NSNoTitle]; + + return s; +} diff --git a/dep/libui/darwin/sierra.h b/dep/libui/darwin/sierra.h new file mode 100644 index 0000000..1a76cb7 --- /dev/null +++ b/dep/libui/darwin/sierra.h @@ -0,0 +1,79 @@ +// 2 june 2017 + +// The OS X 10.12 SDK introduces a number of new names for +// existing constants to align the naming conventions of +// Objective-C and Swift (particularly in AppKit). +// +// Unfortunately, in a baffling move, instead of using the existing +// AvailabilityMacros.h method of marking things deprecated, they +// rewrote the relevant constants in ways that make +// source-compatible building much more annoying: +// +// - The replacement names are now the only names in the enum +// or define sets they used to be in. +// - The old names are provided as static const variables, which +// means any code that used the old names in a switch case now +// spit out a compiler warning in strict C99 mode (TODO and in C++ mode?). +// - The old names are marked with new deprecated-symbol +// macros that are *not* compatible with the AvailabilityMacros.h +// macros, meaning their deprecation warnings still come +// through. (It should be noted that AvailabilityMacros.h was still +// updated for 10.12 regardless, hence our #ifdef below.) +// +// As far as I can gather, these facts are not documented *at all*, so +// in the meantime, other open-source projects just use their own +// #defines to maintain source compatibility, either by making the +// new names available everywhere or the old ones un-deprecated. +// We choose the latter. +// TODO file a radar on the issue (after determining C++ compatibility) so this can be pinned down once and for all +// TODO after that, link my stackoverflow question here too +// TODO make sure this #ifdef does actually work on older systems + +#ifdef MAC_OS_X_VERSION_10_12 + +#define NSControlKeyMask NSEventModifierFlagControl +#define NSAlternateKeyMask NSEventModifierFlagOption +#define NSShiftKeyMask NSEventModifierFlagShift +#define NSCommandKeyMask NSEventModifierFlagCommand + +#define NSLeftMouseDown NSEventTypeLeftMouseDown +#define NSRightMouseDown NSEventTypeRightMouseDown +#define NSOtherMouseDown NSEventTypeOtherMouseDown +#define NSLeftMouseUp NSEventTypeLeftMouseUp +#define NSRightMouseUp NSEventTypeRightMouseUp +#define NSOtherMouseUp NSEventTypeOtherMouseUp +#define NSLeftMouseDragged NSEventTypeLeftMouseDragged +#define NSRightMouseDragged NSEventTypeRightMouseDragged +#define NSOtherMouseDragged NSEventTypeOtherMouseDragged +#define NSKeyDown NSEventTypeKeyDown +#define NSKeyUp NSEventTypeKeyUp +#define NSFlagsChanged NSEventTypeFlagsChanged +#define NSApplicationDefined NSEventTypeApplicationDefined +#define NSPeriodic NSEventTypePeriodic +#define NSMouseMoved NSEventTypeMouseMoved + +#define NSRegularControlSize NSControlSizeRegular +#define NSSmallControlSize NSControlSizeSmall + +#define NSAnyEventMask NSEventMaskAny +#define NSLeftMouseDraggedMask NSEventMaskLeftMouseDragged +#define NSLeftMouseUpMask NSEventMaskLeftMouseUp + +#define NSTickMarkAbove NSTickMarkPositionAbove + +#define NSLinearSlider NSSliderTypeLinear + +#define NSInformationalAlertStyle NSAlertStyleInformational +#define NSCriticalAlertStyle NSAlertStyleCritical + +#define NSBorderlessWindowMask NSWindowStyleMaskBorderless +#define NSTitledWindowMask NSWindowStyleMaskTitled +#define NSClosableWindowMask NSWindowStyleMaskClosable +#define NSMiniaturizableWindowMask NSWindowStyleMaskMiniaturizable +#define NSResizableWindowMask NSWindowStyleMaskResizable + +#endif + +// TODO /Users/pietro/src/github.com/andlabs/libui/darwin/stddialogs.m:83:15: warning: 'beginSheetModalForWindow:modalDelegate:didEndSelector:contextInfo:' is deprecated: first deprecated in macOS 10.10 - Use -beginSheetModalForWindow:completionHandler: instead [-Wdeprecated-declarations] + +// TODO https://developer.apple.com/library/content/releasenotes/Miscellaneous/RN-Foundation-OSX10.12/ diff --git a/dep/libui/darwin/slider.m b/dep/libui/darwin/slider.m new file mode 100644 index 0000000..6f5c5a7 --- /dev/null +++ b/dep/libui/darwin/slider.m @@ -0,0 +1,147 @@ +// 14 august 2015 +#import "uipriv_darwin.h" + +// Horizontal sliders have no intrinsic width; we'll use the default Interface Builder width for them. +// This will also be used for the initial frame size, to ensure the slider is always horizontal (see below). +#define sliderWidth 92 + +@interface libui_intrinsicWidthNSSlider : NSSlider +@end + +@implementation libui_intrinsicWidthNSSlider + +- (NSSize)intrinsicContentSize +{ + NSSize s; + + s = [super intrinsicContentSize]; + s.width = sliderWidth; + return s; +} + +@end + +struct uiSlider { + uiDarwinControl c; + NSSlider *slider; + void (*onChanged)(uiSlider *, void *); + void *onChangedData; +}; + +@interface sliderDelegateClass : NSObject { + uiprivMap *sliders; +} +- (IBAction)onChanged:(id)sender; +- (void)registerSlider:(uiSlider *)b; +- (void)unregisterSlider:(uiSlider *)b; +@end + +@implementation sliderDelegateClass + +- (id)init +{ + self = [super init]; + if (self) + self->sliders = uiprivNewMap(); + return self; +} + +- (void)dealloc +{ + uiprivMapDestroy(self->sliders); + [super dealloc]; +} + +- (IBAction)onChanged:(id)sender +{ + uiSlider *s; + + s = (uiSlider *) uiprivMapGet(self->sliders, sender); + (*(s->onChanged))(s, s->onChangedData); +} + +- (void)registerSlider:(uiSlider *)s +{ + uiprivMapSet(self->sliders, s->slider, s); + [s->slider setTarget:self]; + [s->slider setAction:@selector(onChanged:)]; +} + +- (void)unregisterSlider:(uiSlider *)s +{ + [s->slider setTarget:nil]; + uiprivMapDelete(self->sliders, s->slider); +} + +@end + +static sliderDelegateClass *sliderDelegate = nil; + +uiDarwinControlAllDefaultsExceptDestroy(uiSlider, slider) + +static void uiSliderDestroy(uiControl *c) +{ + uiSlider *s = uiSlider(c); + + [sliderDelegate unregisterSlider:s]; + [s->slider release]; + uiFreeControl(uiControl(s)); +} + +int uiSliderValue(uiSlider *s) +{ + return [s->slider integerValue]; +} + +void uiSliderSetValue(uiSlider *s, int value) +{ + [s->slider setIntegerValue:value]; +} + +void uiSliderOnChanged(uiSlider *s, void (*f)(uiSlider *, void *), void *data) +{ + s->onChanged = f; + s->onChangedData = data; +} + +static void defaultOnChanged(uiSlider *s, void *data) +{ + // do nothing +} + +uiSlider *uiNewSlider(int min, int max) +{ + uiSlider *s; + NSSliderCell *cell; + int temp; + + if (min >= max) { + temp = min; + min = max; + max = temp; + } + + uiDarwinNewControl(uiSlider, s); + + // a horizontal slider is defined as one where the width > height, not by a flag + // to be safe, don't use NSZeroRect, but make it horizontal from the get-go + s->slider = [[libui_intrinsicWidthNSSlider alloc] + initWithFrame:NSMakeRect(0, 0, sliderWidth, 2)]; + [s->slider setMinValue:min]; + [s->slider setMaxValue:max]; + [s->slider setAllowsTickMarkValuesOnly:NO]; + [s->slider setNumberOfTickMarks:0]; + [s->slider setTickMarkPosition:NSTickMarkAbove]; + + cell = (NSSliderCell *) [s->slider cell]; + [cell setSliderType:NSLinearSlider]; + + if (sliderDelegate == nil) { + sliderDelegate = [[sliderDelegateClass new] autorelease]; + [uiprivDelegates addObject:sliderDelegate]; + } + [sliderDelegate registerSlider:s]; + uiSliderOnChanged(s, defaultOnChanged, NULL); + + return s; +} diff --git a/dep/libui/darwin/spinbox.m b/dep/libui/darwin/spinbox.m new file mode 100644 index 0000000..a22ecf1 --- /dev/null +++ b/dep/libui/darwin/spinbox.m @@ -0,0 +1,214 @@ +// 14 august 2015 +#import "uipriv_darwin.h" + +@interface libui_spinbox : NSView { + NSTextField *tf; + NSNumberFormatter *formatter; + NSStepper *stepper; + + NSInteger value; + NSInteger minimum; + NSInteger maximum; + + uiSpinbox *spinbox; +} +- (id)initWithFrame:(NSRect)r spinbox:(uiSpinbox *)sb; +// see https://github.com/andlabs/ui/issues/82 +- (NSInteger)libui_value; +- (void)libui_setValue:(NSInteger)val; +- (void)setMinimum:(NSInteger)min; +- (void)setMaximum:(NSInteger)max; +- (IBAction)stepperClicked:(id)sender; +- (void)controlTextDidChange:(NSNotification *)note; +@end + +struct uiSpinbox { + uiDarwinControl c; + libui_spinbox *spinbox; + void (*onChanged)(uiSpinbox *, void *); + void *onChangedData; +}; + +// yes folks, this varies by operating system! woo! +// 10.10 started drawing the NSStepper one point too low, so we have to fix it up conditionally +// TODO test this; we'll probably have to substitute 10_9 +static CGFloat stepperYDelta(void) +{ + // via https://developer.apple.com/library/mac/releasenotes/AppKit/RN-AppKit/ + if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_9) + return 0; + return -1; +} + +@implementation libui_spinbox + +- (id)initWithFrame:(NSRect)r spinbox:(uiSpinbox *)sb +{ + self = [super initWithFrame:r]; + if (self) { + self->tf = uiprivNewEditableTextField(); + [self->tf setTranslatesAutoresizingMaskIntoConstraints:NO]; + + self->formatter = [NSNumberFormatter new]; + [self->formatter setFormatterBehavior:NSNumberFormatterBehavior10_4]; + [self->formatter setLocalizesFormat:NO]; + [self->formatter setUsesGroupingSeparator:NO]; + [self->formatter setHasThousandSeparators:NO]; + [self->formatter setAllowsFloats:NO]; + [self->tf setFormatter:self->formatter]; + + self->stepper = [[NSStepper alloc] initWithFrame:NSZeroRect]; + [self->stepper setIncrement:1]; + [self->stepper setValueWraps:NO]; + [self->stepper setAutorepeat:YES]; // hold mouse button to step repeatedly + [self->stepper setTranslatesAutoresizingMaskIntoConstraints:NO]; + + [self->tf setDelegate:self]; + [self->stepper setTarget:self]; + [self->stepper setAction:@selector(stepperClicked:)]; + + [self addSubview:self->tf]; + [self addSubview:self->stepper]; + + [self addConstraint:uiprivMkConstraint(self->tf, NSLayoutAttributeLeading, + NSLayoutRelationEqual, + self, NSLayoutAttributeLeading, + 1, 0, + @"uiSpinbox left edge")]; + [self addConstraint:uiprivMkConstraint(self->stepper, NSLayoutAttributeTrailing, + NSLayoutRelationEqual, + self, NSLayoutAttributeTrailing, + 1, 0, + @"uiSpinbox right edge")]; + [self addConstraint:uiprivMkConstraint(self->tf, NSLayoutAttributeTop, + NSLayoutRelationEqual, + self, NSLayoutAttributeTop, + 1, 0, + @"uiSpinbox top edge text field")]; + [self addConstraint:uiprivMkConstraint(self->tf, NSLayoutAttributeBottom, + NSLayoutRelationEqual, + self, NSLayoutAttributeBottom, + 1, 0, + @"uiSpinbox bottom edge text field")]; + [self addConstraint:uiprivMkConstraint(self->stepper, NSLayoutAttributeTop, + NSLayoutRelationEqual, + self, NSLayoutAttributeTop, + 1, stepperYDelta(), + @"uiSpinbox top edge stepper")]; + [self addConstraint:uiprivMkConstraint(self->stepper, NSLayoutAttributeBottom, + NSLayoutRelationEqual, + self, NSLayoutAttributeBottom, + 1, stepperYDelta(), + @"uiSpinbox bottom edge stepper")]; + [self addConstraint:uiprivMkConstraint(self->tf, NSLayoutAttributeTrailing, + NSLayoutRelationEqual, + self->stepper, NSLayoutAttributeLeading, + 1, -3, // arbitrary amount; good enough visually (and it seems to match NSDatePicker too, at least on 10.11, which is even better) + @"uiSpinbox space between text field and stepper")]; + + self->spinbox = sb; + } + return self; +} + +- (void)dealloc +{ + [self->tf setDelegate:nil]; + [self->tf removeFromSuperview]; + [self->tf release]; + [self->formatter release]; + [self->stepper setTarget:nil]; + [self->stepper removeFromSuperview]; + [self->stepper release]; + [super dealloc]; +} + +- (NSInteger)libui_value +{ + return self->value; +} + +- (void)libui_setValue:(NSInteger)val +{ + self->value = val; + if (self->value < self->minimum) + self->value = self->minimum; + if (self->value > self->maximum) + self->value = self->maximum; + [self->tf setIntegerValue:self->value]; + [self->stepper setIntegerValue:self->value]; +} + +- (void)setMinimum:(NSInteger)min +{ + self->minimum = min; + [self->formatter setMinimum:[NSNumber numberWithInteger:self->minimum]]; + [self->stepper setMinValue:((double) (self->minimum))]; +} + +- (void)setMaximum:(NSInteger)max +{ + self->maximum = max; + [self->formatter setMaximum:[NSNumber numberWithInteger:self->maximum]]; + [self->stepper setMaxValue:((double) (self->maximum))]; +} + +- (IBAction)stepperClicked:(id)sender +{ + [self libui_setValue:[self->stepper integerValue]]; + (*(self->spinbox->onChanged))(self->spinbox, self->spinbox->onChangedData); +} + +- (void)controlTextDidChange:(NSNotification *)note +{ + [self libui_setValue:[self->tf integerValue]]; + (*(self->spinbox->onChanged))(self->spinbox, self->spinbox->onChangedData); +} + +@end + +uiDarwinControlAllDefaults(uiSpinbox, spinbox) + +int uiSpinboxValue(uiSpinbox *s) +{ + return [s->spinbox libui_value]; +} + +void uiSpinboxSetValue(uiSpinbox *s, int value) +{ + [s->spinbox libui_setValue:value]; +} + +void uiSpinboxOnChanged(uiSpinbox *s, void (*f)(uiSpinbox *, void *), void *data) +{ + s->onChanged = f; + s->onChangedData = data; +} + +static void defaultOnChanged(uiSpinbox *s, void *data) +{ + // do nothing +} + +uiSpinbox *uiNewSpinbox(int min, int max) +{ + uiSpinbox *s; + int temp; + + if (min >= max) { + temp = min; + min = max; + max = temp; + } + + uiDarwinNewControl(uiSpinbox, s); + + s->spinbox = [[libui_spinbox alloc] initWithFrame:NSZeroRect spinbox:s]; + [s->spinbox setMinimum:min]; + [s->spinbox setMaximum:max]; + [s->spinbox libui_setValue:min]; + + uiSpinboxOnChanged(s, defaultOnChanged, NULL); + + return s; +} diff --git a/dep/libui/darwin/stddialogs.m b/dep/libui/darwin/stddialogs.m new file mode 100644 index 0000000..814456a --- /dev/null +++ b/dep/libui/darwin/stddialogs.m @@ -0,0 +1,123 @@ +// 26 june 2015 +#import "uipriv_darwin.h" + +// LONGTERM restructure this whole file +// LONGTERM explicitly document this works as we want +// LONGTERM note that font and color buttons also do this + +#define windowWindow(w) ((NSWindow *) uiControlHandle(uiControl(w))) + +// source of code modal logic: http://stackoverflow.com/questions/604768/wait-for-nsalert-beginsheetmodalforwindow + +// note: whether extensions are actually shown depends on a user setting in Finder; we can't control it here +static void setupSavePanel(NSSavePanel *s) +{ + [s setCanCreateDirectories:YES]; + [s setShowsHiddenFiles:YES]; + [s setExtensionHidden:NO]; + [s setCanSelectHiddenExtension:NO]; + [s setTreatsFilePackagesAsDirectories:YES]; +} + +static char *runSavePanel(NSWindow *parent, NSSavePanel *s) +{ + char *filename; + + [s beginSheetModalForWindow:parent completionHandler:^(NSInteger result) { + [uiprivNSApp() stopModalWithCode:result]; + }]; + if ([uiprivNSApp() runModalForWindow:s] != NSFileHandlingPanelOKButton) + return NULL; + filename = uiDarwinNSStringToText([[s URL] path]); + return filename; +} + +char *uiOpenFile(uiWindow *parent) +{ + NSOpenPanel *o; + + o = [NSOpenPanel openPanel]; + [o setCanChooseFiles:YES]; + [o setCanChooseDirectories:NO]; + [o setResolvesAliases:NO]; + [o setAllowsMultipleSelection:NO]; + setupSavePanel(o); + // panel is autoreleased + return runSavePanel(windowWindow(parent), o); +} + +char *uiSaveFile(uiWindow *parent) +{ + NSSavePanel *s; + + s = [NSSavePanel savePanel]; + setupSavePanel(s); + // panel is autoreleased + return runSavePanel(windowWindow(parent), s); +} + +// I would use a completion handler for NSAlert as well, but alas NSAlert's are 10.9 and higher only +@interface libuiCodeModalAlertPanel : NSObject { + NSAlert *panel; + NSWindow *parent; +} +- (id)initWithPanel:(NSAlert *)p parent:(NSWindow *)w; +- (NSInteger)run; +- (void)panelEnded:(NSAlert *)panel result:(NSInteger)result data:(void *)data; +@end + +@implementation libuiCodeModalAlertPanel + +- (id)initWithPanel:(NSAlert *)p parent:(NSWindow *)w +{ + self = [super init]; + if (self) { + self->panel = p; + self->parent = w; + } + return self; +} + +- (NSInteger)run +{ + [self->panel beginSheetModalForWindow:self->parent + modalDelegate:self + didEndSelector:@selector(panelEnded:result:data:) + contextInfo:NULL]; + return [uiprivNSApp() runModalForWindow:[self->panel window]]; +} + +- (void)panelEnded:(NSAlert *)panel result:(NSInteger)result data:(void *)data +{ + [uiprivNSApp() stopModalWithCode:result]; +} + +@end + +static void msgbox(NSWindow *parent, const char *title, const char *description, NSAlertStyle style) +{ + NSAlert *a; + libuiCodeModalAlertPanel *cm; + + a = [NSAlert new]; + [a setAlertStyle:style]; + [a setShowsHelp:NO]; + [a setShowsSuppressionButton:NO]; + [a setMessageText:uiprivToNSString(title)]; + [a setInformativeText:uiprivToNSString(description)]; + [a addButtonWithTitle:@"OK"]; + cm = [[libuiCodeModalAlertPanel alloc] initWithPanel:a parent:parent]; + [cm run]; + [cm release]; + [a release]; +} + +void uiMsgBox(uiWindow *parent, const char *title, const char *description) +{ + msgbox(windowWindow(parent), title, description, NSInformationalAlertStyle); +} + +void uiMsgBoxError(uiWindow *parent, const char *title, const char *description) +{ + msgbox(windowWindow(parent), title, description, NSCriticalAlertStyle); +} diff --git a/dep/libui/darwin/tab.m b/dep/libui/darwin/tab.m new file mode 100644 index 0000000..28c3831 --- /dev/null +++ b/dep/libui/darwin/tab.m @@ -0,0 +1,292 @@ +// 15 august 2015 +#import "uipriv_darwin.h" + +// TODO need to jiggle on tab change too (second page disabled tab label initially ambiguous) + +@interface tabPage : NSObject { + uiprivSingleChildConstraints constraints; + int margined; + NSView *view; // the NSTabViewItem view itself + NSObject *pageID; +} +@property uiControl *c; +@property NSLayoutPriority oldHorzHuggingPri; +@property NSLayoutPriority oldVertHuggingPri; +- (id)initWithView:(NSView *)v pageID:(NSObject *)o; +- (NSView *)childView; +- (void)establishChildConstraints; +- (void)removeChildConstraints; +- (int)isMargined; +- (void)setMargined:(int)m; +@end + +struct uiTab { + uiDarwinControl c; + NSTabView *tabview; + NSMutableArray *pages; + NSLayoutPriority horzHuggingPri; + NSLayoutPriority vertHuggingPri; +}; + +@implementation tabPage + +- (id)initWithView:(NSView *)v pageID:(NSObject *)o +{ + self = [super init]; + if (self != nil) { + self->view = [v retain]; + self->pageID = [o retain]; + } + return self; +} + +- (void)dealloc +{ + [self removeChildConstraints]; + [self->view release]; + [self->pageID release]; + [super dealloc]; +} + +- (NSView *)childView +{ + return (NSView *) uiControlHandle(self.c); +} + +- (void)establishChildConstraints +{ + [self removeChildConstraints]; + if (self.c == NULL) + return; + uiprivSingleChildConstraintsEstablish(&(self->constraints), + self->view, [self childView], + uiDarwinControlHugsTrailingEdge(uiDarwinControl(self.c)), + uiDarwinControlHugsBottom(uiDarwinControl(self.c)), + self->margined, + @"uiTab page"); +} + +- (void)removeChildConstraints +{ + uiprivSingleChildConstraintsRemove(&(self->constraints), self->view); +} + +- (int)isMargined +{ + return self->margined; +} + +- (void)setMargined:(int)m +{ + self->margined = m; + uiprivSingleChildConstraintsSetMargined(&(self->constraints), self->margined); +} + +@end + +static void uiTabDestroy(uiControl *c) +{ + uiTab *t = uiTab(c); + tabPage *page; + + // first remove all tab pages so we can destroy all the children + while ([t->tabview numberOfTabViewItems] != 0) + [t->tabview removeTabViewItem:[t->tabview tabViewItemAtIndex:0]]; + // then destroy all the children + for (page in t->pages) { + [page removeChildConstraints]; + uiControlSetParent(page.c, NULL); + uiDarwinControlSetSuperview(uiDarwinControl(page.c), nil); + uiControlDestroy(page.c); + } + // and finally destroy ourselves + [t->pages release]; + [t->tabview release]; + uiFreeControl(uiControl(t)); +} + +uiDarwinControlDefaultHandle(uiTab, tabview) +uiDarwinControlDefaultParent(uiTab, tabview) +uiDarwinControlDefaultSetParent(uiTab, tabview) +uiDarwinControlDefaultToplevel(uiTab, tabview) +uiDarwinControlDefaultVisible(uiTab, tabview) +uiDarwinControlDefaultShow(uiTab, tabview) +uiDarwinControlDefaultHide(uiTab, tabview) +uiDarwinControlDefaultEnabled(uiTab, tabview) +uiDarwinControlDefaultEnable(uiTab, tabview) +uiDarwinControlDefaultDisable(uiTab, tabview) + +static void uiTabSyncEnableState(uiDarwinControl *c, int enabled) +{ + uiTab *t = uiTab(c); + tabPage *page; + + if (uiDarwinShouldStopSyncEnableState(uiDarwinControl(t), enabled)) + return; + for (page in t->pages) + uiDarwinControlSyncEnableState(uiDarwinControl(page.c), enabled); +} + +uiDarwinControlDefaultSetSuperview(uiTab, tabview) + +static void tabRelayout(uiTab *t) +{ + tabPage *page; + + for (page in t->pages) + [page establishChildConstraints]; + // and this gets rid of some weird issues with regards to box alignment + uiprivJiggleViewLayout(t->tabview); +} + +BOOL uiTabHugsTrailingEdge(uiDarwinControl *c) +{ + uiTab *t = uiTab(c); + + return t->horzHuggingPri < NSLayoutPriorityWindowSizeStayPut; +} + +BOOL uiTabHugsBottom(uiDarwinControl *c) +{ + uiTab *t = uiTab(c); + + return t->vertHuggingPri < NSLayoutPriorityWindowSizeStayPut; +} + +static void uiTabChildEdgeHuggingChanged(uiDarwinControl *c) +{ + uiTab *t = uiTab(c); + + tabRelayout(t); +} + +static NSLayoutPriority uiTabHuggingPriority(uiDarwinControl *c, NSLayoutConstraintOrientation orientation) +{ + uiTab *t = uiTab(c); + + if (orientation == NSLayoutConstraintOrientationHorizontal) + return t->horzHuggingPri; + return t->vertHuggingPri; +} + +static void uiTabSetHuggingPriority(uiDarwinControl *c, NSLayoutPriority priority, NSLayoutConstraintOrientation orientation) +{ + uiTab *t = uiTab(c); + + if (orientation == NSLayoutConstraintOrientationHorizontal) + t->horzHuggingPri = priority; + else + t->vertHuggingPri = priority; + uiDarwinNotifyEdgeHuggingChanged(uiDarwinControl(t)); +} + +static void uiTabChildVisibilityChanged(uiDarwinControl *c) +{ + uiTab *t = uiTab(c); + + tabRelayout(t); +} + +void uiTabAppend(uiTab *t, const char *name, uiControl *child) +{ + uiTabInsertAt(t, name, [t->pages count], child); +} + +void uiTabInsertAt(uiTab *t, const char *name, int n, uiControl *child) +{ + tabPage *page; + NSView *view; + NSTabViewItem *i; + NSObject *pageID; + + uiControlSetParent(child, uiControl(t)); + + view = [[[NSView alloc] initWithFrame:NSZeroRect] autorelease]; + // note: if we turn off the autoresizing mask, nothing shows up + uiDarwinControlSetSuperview(uiDarwinControl(child), view); + uiDarwinControlSyncEnableState(uiDarwinControl(child), uiControlEnabledToUser(uiControl(t))); + + // the documentation says these can be nil but the headers say these must not be; let's be safe and make them non-nil anyway + pageID = [NSObject new]; + page = [[[tabPage alloc] initWithView:view pageID:pageID] autorelease]; + page.c = child; + + // don't hug, just in case we're a stretchy tab + page.oldHorzHuggingPri = uiDarwinControlHuggingPriority(uiDarwinControl(page.c), NSLayoutConstraintOrientationHorizontal); + page.oldVertHuggingPri = uiDarwinControlHuggingPriority(uiDarwinControl(page.c), NSLayoutConstraintOrientationVertical); + uiDarwinControlSetHuggingPriority(uiDarwinControl(page.c), NSLayoutPriorityDefaultLow, NSLayoutConstraintOrientationHorizontal); + uiDarwinControlSetHuggingPriority(uiDarwinControl(page.c), NSLayoutPriorityDefaultLow, NSLayoutConstraintOrientationVertical); + + [t->pages insertObject:page atIndex:n]; + + i = [[[NSTabViewItem alloc] initWithIdentifier:pageID] autorelease]; + [i setLabel:uiprivToNSString(name)]; + [i setView:view]; + [t->tabview insertTabViewItem:i atIndex:n]; + + tabRelayout(t); +} + +void uiTabDelete(uiTab *t, int n) +{ + tabPage *page; + uiControl *child; + NSTabViewItem *i; + + page = (tabPage *) [t->pages objectAtIndex:n]; + + uiDarwinControlSetHuggingPriority(uiDarwinControl(page.c), page.oldHorzHuggingPri, NSLayoutConstraintOrientationHorizontal); + uiDarwinControlSetHuggingPriority(uiDarwinControl(page.c), page.oldVertHuggingPri, NSLayoutConstraintOrientationVertical); + + child = page.c; + [page removeChildConstraints]; + [t->pages removeObjectAtIndex:n]; + + uiControlSetParent(child, NULL); + uiDarwinControlSetSuperview(uiDarwinControl(child), nil); + + i = [t->tabview tabViewItemAtIndex:n]; + [t->tabview removeTabViewItem:i]; + + tabRelayout(t); +} + +int uiTabNumPages(uiTab *t) +{ + return [t->pages count]; +} + +int uiTabMargined(uiTab *t, int n) +{ + tabPage *page; + + page = (tabPage *) [t->pages objectAtIndex:n]; + return [page isMargined]; +} + +void uiTabSetMargined(uiTab *t, int n, int margined) +{ + tabPage *page; + + page = (tabPage *) [t->pages objectAtIndex:n]; + [page setMargined:margined]; +} + +uiTab *uiNewTab(void) +{ + uiTab *t; + + uiDarwinNewControl(uiTab, t); + + t->tabview = [[NSTabView alloc] initWithFrame:NSZeroRect]; + // also good for NSTabView (same selector and everything) + uiDarwinSetControlFont((NSControl *) (t->tabview), NSRegularControlSize); + + t->pages = [NSMutableArray new]; + + // default to low hugging to not hug edges + t->horzHuggingPri = NSLayoutPriorityDefaultLow; + t->vertHuggingPri = NSLayoutPriorityDefaultLow; + + return t; +} diff --git a/dep/libui/darwin/table.h b/dep/libui/darwin/table.h new file mode 100644 index 0000000..4146ab7 --- /dev/null +++ b/dep/libui/darwin/table.h @@ -0,0 +1,27 @@ +// 3 june 2018 +#import "../common/table.h" + +// table.m +// TODO get rid of forward declaration +@class uiprivTableModel; +struct uiTableModel { + uiTableModelHandler *mh; + uiprivTableModel *m; + NSMutableArray *tables; +}; +struct uiTable { + uiDarwinControl c; + NSScrollView *sv; + NSTableView *tv; + uiprivScrollViewData *d; + int backgroundColumn; + uiTableModel *m; +}; + +// tablecolumn.m +@interface uiprivTableCellView : NSTableCellView +- (void)uiprivUpdate:(NSInteger)row; +@end +@interface uiprivTableColumn : NSTableColumn +- (uiprivTableCellView *)uiprivMakeCellView; +@end diff --git a/dep/libui/darwin/table.m b/dep/libui/darwin/table.m new file mode 100644 index 0000000..1bdc7f8 --- /dev/null +++ b/dep/libui/darwin/table.m @@ -0,0 +1,218 @@ +// 3 june 2018 +#import "uipriv_darwin.h" +#import "table.h" + +// TODO is the initial scroll position still wrong? + +@interface uiprivTableModel : NSObject { + uiTableModel *m; +} +- (id)initWithModel:(uiTableModel *)model; +@end + +// TODO we really need to clean up the sharing of the table and model variables... +@interface uiprivTableView : NSTableView { + uiTable *uiprivT; + uiTableModel *uiprivM; +} +- (id)initWithFrame:(NSRect)r uiprivT:(uiTable *)t uiprivM:(uiTableModel *)m; +@end + +@implementation uiprivTableView + +- (id)initWithFrame:(NSRect)r uiprivT:(uiTable *)t uiprivM:(uiTableModel *)m +{ + self = [super initWithFrame:r]; + if (self) { + self->uiprivT = t; + self->uiprivM = m; + } + return self; +} + +// TODO is this correct for overflow scrolling? +static void setBackgroundColor(uiprivTableView *t, NSTableRowView *rv, NSInteger row) +{ + NSColor *color; + double r, g, b, a; + + if (t->uiprivT->backgroundColumn == -1) + return; // let Cocoa do its default thing + if (uiprivTableModelColorIfProvided(t->uiprivM, row, t->uiprivT->backgroundColumn, &r, &g, &b, &a)) + color = [NSColor colorWithSRGBRed:r green:g blue:b alpha:a]; + else { + NSArray *colors; + NSInteger index; + + // this usage is primarily a guess; hopefully it is correct for the non-two color case... (TODO) + // it does seem to be correct for the two-color case, judging from comparing against the value of backgroundColor before changing it (and no, nil does not work; it just sets to white) + colors = [NSColor controlAlternatingRowBackgroundColors]; + index = row % [colors count]; + color = (NSColor *) [colors objectAtIndex:index]; + } + [rv setBackgroundColor:color]; + // color is autoreleased in all cases +} + +@end + +@implementation uiprivTableModel + +- (id)initWithModel:(uiTableModel *)model +{ + self = [super init]; + if (self) + self->m = model; + return self; +} + +- (NSInteger)numberOfRowsInTableView:(NSTableView *)tv +{ + return uiprivTableModelNumRows(self->m); +} + + - (NSView *)tableView:(NSTableView *)tv viewForTableColumn:(NSTableColumn *)cc row:(NSInteger)row +{ + uiprivTableColumn *c = (uiprivTableColumn *) cc; + uiprivTableCellView *cv; + + cv = (uiprivTableCellView *) [tv makeViewWithIdentifier:[c identifier] owner:self]; + if (cv == nil) + cv = [c uiprivMakeCellView]; + [cv uiprivUpdate:row]; + return cv; +} + +- (void)tableView:(NSTableView *)tv didAddRowView:(NSTableRowView *)rv forRow:(NSInteger)row +{ + setBackgroundColor((uiprivTableView *) tv, rv, row); +} + +@end + +uiTableModel *uiNewTableModel(uiTableModelHandler *mh) +{ + uiTableModel *m; + + m = uiprivNew(uiTableModel); + m->mh = mh; + m->m = [[uiprivTableModel alloc] initWithModel:m]; + m->tables = [NSMutableArray new]; + return m; +} + +void uiFreeTableModel(uiTableModel *m) +{ + if ([m->tables count] != 0) + uiprivUserBug("You cannot free a uiTableModel while uiTables are using it."); + [m->tables release]; + [m->m release]; + uiprivFree(m); +} + +void uiTableModelRowInserted(uiTableModel *m, int newIndex) +{ + NSTableView *tv; + NSIndexSet *set; + + set = [NSIndexSet indexSetWithIndex:newIndex]; + for (tv in m->tables) + [tv insertRowsAtIndexes:set withAnimation:NSTableViewAnimationEffectNone]; + // set is autoreleased +} + +void uiTableModelRowChanged(uiTableModel *m, int index) +{ + uiprivTableView *tv; + NSTableRowView *rv; + NSUInteger i, n; + uiprivTableCellView *cv; + + for (tv in m->tables) { + rv = [tv rowViewAtRow:index makeIfNecessary:NO]; + if (rv != nil) + setBackgroundColor(tv, rv, index); + n = [[tv tableColumns] count]; + for (i = 0; i < n; i++) { + cv = (uiprivTableCellView *) [tv viewAtColumn:i row:index makeIfNecessary:NO]; + if (cv != nil) + [cv uiprivUpdate:index]; + } + } +} + +void uiTableModelRowDeleted(uiTableModel *m, int oldIndex) +{ + NSTableView *tv; + NSIndexSet *set; + + set = [NSIndexSet indexSetWithIndex:oldIndex]; + for (tv in m->tables) + [tv removeRowsAtIndexes:set withAnimation:NSTableViewAnimationEffectNone]; + // set is autoreleased +} + +uiTableModelHandler *uiprivTableModelHandler(uiTableModel *m) +{ + return m->mh; +} + +uiDarwinControlAllDefaultsExceptDestroy(uiTable, sv) + +static void uiTableDestroy(uiControl *c) +{ + uiTable *t = uiTable(c); + + [t->m->tables removeObject:t->tv]; + uiprivScrollViewFreeData(t->sv, t->d); + [t->tv release]; + [t->sv release]; + uiFreeControl(uiControl(t)); +} + +uiTable *uiNewTable(uiTableParams *p) +{ + uiTable *t; + uiprivScrollViewCreateParams sp; + + uiDarwinNewControl(uiTable, t); + t->m = p->Model; + t->backgroundColumn = p->RowBackgroundColorModelColumn; + + t->tv = [[uiprivTableView alloc] initWithFrame:NSZeroRect uiprivT:t uiprivM:t->m]; + + [t->tv setDataSource:t->m->m]; + [t->tv setDelegate:t->m->m]; + [t->tv reloadData]; + [t->m->tables addObject:t->tv]; + + // TODO is this sufficient? + [t->tv setAllowsColumnReordering:NO]; + [t->tv setAllowsColumnResizing:YES]; + [t->tv setAllowsMultipleSelection:NO]; + [t->tv setAllowsEmptySelection:YES]; + [t->tv setAllowsColumnSelection:NO]; + [t->tv setUsesAlternatingRowBackgroundColors:YES]; + [t->tv setSelectionHighlightStyle:NSTableViewSelectionHighlightStyleRegular]; + [t->tv setGridStyleMask:NSTableViewGridNone]; + [t->tv setAllowsTypeSelect:YES]; + // TODO floatsGroupRows — do we even allow group rows? + + memset(&sp, 0, sizeof (uiprivScrollViewCreateParams)); + sp.DocumentView = t->tv; + // this is what Interface Builder sets it to + // TODO verify + sp.BackgroundColor = [NSColor colorWithCalibratedWhite:1.0 alpha:1.0]; + sp.DrawsBackground = YES; + sp.Bordered = YES; + sp.HScroll = YES; + sp.VScroll = YES; + t->sv = uiprivMkScrollView(&sp, &(t->d)); + + // TODO WHY DOES THIS REMOVE ALL GRAPHICAL GLITCHES? + // I got the idea from http://jwilling.com/blog/optimized-nstableview-scrolling/ but that was on an unrelated problem I didn't seem to have (although I have small-ish tables to start with) + // I don't get layer-backing... am I supposed to layer-back EVERYTHING manually? I need to check Interface Builder again... + [t->sv setWantsLayer:YES]; + + return t; +} diff --git a/dep/libui/darwin/tablecolumn.m b/dep/libui/darwin/tablecolumn.m new file mode 100644 index 0000000..5038cc6 --- /dev/null +++ b/dep/libui/darwin/tablecolumn.m @@ -0,0 +1,720 @@ +// 3 june 2018 +#import "uipriv_darwin.h" +#import "table.h" + +// values from interface builder +#define textColumnLeading 2 +#define textColumnTrailing 2 +#define imageColumnLeading 3 +#define imageTextColumnLeading 7 +#define checkboxTextColumnLeading 0 +// these aren't provided by IB; let's just choose one +#define checkboxColumnLeading imageColumnLeading +#define progressBarColumnLeading imageColumnLeading +#define progressBarColumnTrailing progressBarColumnLeading +#define buttonColumnLeading imageColumnLeading +#define buttonColumnTrailing buttonColumnLeading + +@implementation uiprivTableCellView + +- (void)uiprivUpdate:(NSInteger)row +{ + [self doesNotRecognizeSelector:_cmd]; +} + +@end + +@implementation uiprivTableColumn + +- (uiprivTableCellView *)uiprivMakeCellView +{ + [self doesNotRecognizeSelector:_cmd]; + return nil; // appease compiler +} + +@end + +struct textColumnCreateParams { + uiTable *t; + uiTableModel *m; + + BOOL makeTextField; + int textModelColumn; + int textEditableModelColumn; + uiTableTextColumnOptionalParams textParams; + + BOOL makeImageView; + int imageModelColumn; + + BOOL makeCheckbox; + int checkboxModelColumn; + int checkboxEditableModelColumn; +}; + +@interface uiprivTextImageCheckboxTableCellView : uiprivTableCellView { + uiTable *t; + uiTableModel *m; + + NSTextField *tf; + int textModelColumn; + int textEditableModelColumn; + uiTableTextColumnOptionalParams textParams; + + NSImageView *iv; + int imageModelColumn; + + NSButton *cb; + int checkboxModelColumn; + int checkboxEditableModelColumn; +} +- (id)initWithFrame:(NSRect)r params:(struct textColumnCreateParams *)p; +- (IBAction)uiprivOnTextFieldAction:(id)sender; +- (IBAction)uiprivOnCheckboxAction:(id)sender; +@end + +@implementation uiprivTextImageCheckboxTableCellView + +- (id)initWithFrame:(NSRect)r params:(struct textColumnCreateParams *)p +{ + self = [super initWithFrame:r]; + if (self) { + NSMutableArray *constraints; + + self->t = p->t; + self->m = p->m; + constraints = [NSMutableArray new]; + + self->tf = nil; + if (p->makeTextField) { + self->textModelColumn = p->textModelColumn; + self->textEditableModelColumn = p->textEditableModelColumn; + self->textParams = p->textParams; + + self->tf = uiprivNewLabel(@""); + // TODO set wrap and ellipsize modes? + [self->tf setTarget:self]; + [self->tf setAction:@selector(uiprivOnTextFieldAction:)]; + [self->tf setTranslatesAutoresizingMaskIntoConstraints:NO]; + [self addSubview:self->tf]; + + // TODO for all three controls: set hugging and compression resistance properly + [constraints addObject:uiprivMkConstraint(self, NSLayoutAttributeLeading, + NSLayoutRelationEqual, + self->tf, NSLayoutAttributeLeading, + 1, -textColumnLeading, + @"uiTable cell text leading constraint")]; + [constraints addObject:uiprivMkConstraint(self, NSLayoutAttributeTop, + NSLayoutRelationEqual, + self->tf, NSLayoutAttributeTop, + 1, 0, + @"uiTable cell text top constraint")]; + [constraints addObject:uiprivMkConstraint(self, NSLayoutAttributeTrailing, + NSLayoutRelationEqual, + self->tf, NSLayoutAttributeTrailing, + 1, textColumnTrailing, + @"uiTable cell text trailing constraint")]; + [constraints addObject:uiprivMkConstraint(self, NSLayoutAttributeBottom, + NSLayoutRelationEqual, + self->tf, NSLayoutAttributeBottom, + 1, 0, + @"uiTable cell text bottom constraint")]; + } + + self->iv = nil; + if (p->makeImageView) { + self->imageModelColumn = p->imageModelColumn; + + self->iv = [[NSImageView alloc] initWithFrame:NSZeroRect]; + [self->iv setImageFrameStyle:NSImageFrameNone]; + [self->iv setImageAlignment:NSImageAlignCenter]; + [self->iv setImageScaling:NSImageScaleProportionallyDown]; + [self->iv setAnimates:NO]; + [self->iv setEditable:NO]; + [self->iv setTranslatesAutoresizingMaskIntoConstraints:NO]; + [self addSubview:self->iv]; + + [constraints addObject:uiprivMkConstraint(self->iv, NSLayoutAttributeWidth, + NSLayoutRelationEqual, + self->iv, NSLayoutAttributeHeight, + 1, 0, + @"uiTable image squareness constraint")]; + if (self->tf != nil) { + [constraints addObject:uiprivMkConstraint(self, NSLayoutAttributeLeading, + NSLayoutRelationEqual, + self->iv, NSLayoutAttributeLeading, + 1, -imageColumnLeading, + @"uiTable cell image leading constraint")]; + [constraints replaceObjectAtIndex:0 + withObject:uiprivMkConstraint(self->iv, NSLayoutAttributeTrailing, + NSLayoutRelationEqual, + self->tf, NSLayoutAttributeLeading, + 1, -imageTextColumnLeading, + @"uiTable cell image-text spacing constraint")]; + } else + [constraints addObject:uiprivMkConstraint(self, NSLayoutAttributeCenterX, + NSLayoutRelationEqual, + self->iv, NSLayoutAttributeCenterX, + 1, 0, + @"uiTable cell image centering constraint")]; + [constraints addObject:uiprivMkConstraint(self, NSLayoutAttributeTop, + NSLayoutRelationEqual, + self->iv, NSLayoutAttributeTop, + 1, 0, + @"uiTable cell image top constraint")]; + [constraints addObject:uiprivMkConstraint(self, NSLayoutAttributeBottom, + NSLayoutRelationEqual, + self->iv, NSLayoutAttributeBottom, + 1, 0, + @"uiTable cell image bottom constraint")]; + } + + self->cb = nil; + if (p->makeCheckbox) { + self->checkboxModelColumn = p->checkboxModelColumn; + self->checkboxEditableModelColumn = p->checkboxEditableModelColumn; + + self->cb = [[NSButton alloc] initWithFrame:NSZeroRect]; + [self->cb setTitle:@""]; + [self->cb setButtonType:NSSwitchButton]; + // doesn't seem to have an associated bezel style + [self->cb setBordered:NO]; + [self->cb setTransparent:NO]; + uiDarwinSetControlFont(self->cb, NSRegularControlSize); + [self->cb setTranslatesAutoresizingMaskIntoConstraints:NO]; + [self addSubview:self->cb]; + + if (self->tf != nil) { + [constraints addObject:uiprivMkConstraint(self, NSLayoutAttributeLeading, + NSLayoutRelationEqual, + self->cb, NSLayoutAttributeLeading, + 1, -imageColumnLeading, + @"uiTable cell checkbox leading constraint")]; + [constraints replaceObjectAtIndex:0 + withObject:uiprivMkConstraint(self->cb, NSLayoutAttributeTrailing, + NSLayoutRelationEqual, + self->tf, NSLayoutAttributeLeading, + 1, -imageTextColumnLeading, + @"uiTable cell checkbox-text spacing constraint")]; + } else + [constraints addObject:uiprivMkConstraint(self, NSLayoutAttributeCenterX, + NSLayoutRelationEqual, + self->cb, NSLayoutAttributeCenterX, + 1, 0, + @"uiTable cell checkbox centering constraint")]; + [constraints addObject:uiprivMkConstraint(self, NSLayoutAttributeTop, + NSLayoutRelationEqual, + self->cb, NSLayoutAttributeTop, + 1, 0, + @"uiTable cell checkbox top constraint")]; + [constraints addObject:uiprivMkConstraint(self, NSLayoutAttributeBottom, + NSLayoutRelationEqual, + self->cb, NSLayoutAttributeBottom, + 1, 0, + @"uiTable cell checkbox bottom constraint")]; + } + + [self addConstraints:constraints]; + + // take advantage of NSTableCellView-provided accessibility features + if (self->tf != nil) + [self setTextField:self->tf]; + if (self->iv != nil) + [self setImageView:self->iv]; + } + return self; +} + +- (void)dealloc +{ + if (self->cb != nil) { + [self->cb release]; + self->cb = nil; + } + if (self->iv != nil) { + [self->iv release]; + self->iv = nil; + } + if (self->tf != nil) { + [self->tf release]; + self->tf = nil; + } + [super dealloc]; +} + +- (void)uiprivUpdate:(NSInteger)row +{ + uiTableValue *value; + + if (self->tf != nil) { + NSString *str; + NSColor *color; + double r, g, b, a; + + value = uiprivTableModelCellValue(self->m, row, self->textModelColumn); + str = uiprivToNSString(uiTableValueString(value)); + uiFreeTableValue(value); + [self->tf setStringValue:str]; + + [self->tf setEditable:uiprivTableModelCellEditable(self->m, row, self->textEditableModelColumn)]; + + color = [NSColor controlTextColor]; + if (uiprivTableModelColorIfProvided(self->m, row, self->textParams.ColorModelColumn, &r, &g, &b, &a)) + color = [NSColor colorWithSRGBRed:r green:g blue:b alpha:a]; + [self->tf setTextColor:color]; + // we don't own color in ether case; don't release + } + if (self->iv != nil) { + uiImage *img; + + value = uiprivTableModelCellValue(self->m, row, self->imageModelColumn); + img = uiTableValueImage(value); + uiFreeTableValue(value); + [self->iv setImage:uiprivImageNSImage(img)]; + } + if (self->cb != nil) { + value = uiprivTableModelCellValue(self->m, row, self->checkboxModelColumn); + if (uiTableValueInt(value) != 0) + [self->cb setState:NSOnState]; + else + [self->cb setState:NSOffState]; + uiFreeTableValue(value); + + [self->cb setEnabled:uiprivTableModelCellEditable(self->m, row, self->checkboxEditableModelColumn)]; + } +} + +- (IBAction)uiprivOnTextFieldAction:(id)sender +{ + NSInteger row; + uiTableValue *value; + + row = [self->t->tv rowForView:self->tf]; + value = uiNewTableValueString([[self->tf stringValue] UTF8String]); + uiprivTableModelSetCellValue(self->m, row, self->textModelColumn, value); + uiFreeTableValue(value); + // always refresh the value in case the model rejected it + // TODO document that we do this, but not for the whole row (or decide to do both, or do neither...) + [self uiprivUpdate:row]; +} + +- (IBAction)uiprivOnCheckboxAction:(id)sender +{ + NSInteger row; + uiTableValue *value; + + row = [self->t->tv rowForView:self->cb]; + value = uiNewTableValueInt([self->cb state] != NSOffState); + uiprivTableModelSetCellValue(self->m, row, self->checkboxModelColumn, value); + uiFreeTableValue(value); + // always refresh the value in case the model rejected it + [self uiprivUpdate:row]; +} + +@end + +@interface uiprivTextImageCheckboxTableColumn : uiprivTableColumn { + struct textColumnCreateParams params; +} +- (id)initWithIdentifier:(NSString *)ident params:(struct textColumnCreateParams *)p; +@end + +@implementation uiprivTextImageCheckboxTableColumn + +- (id)initWithIdentifier:(NSString *)ident params:(struct textColumnCreateParams *)p +{ + self = [super initWithIdentifier:ident]; + if (self) + self->params = *p; + return self; +} + +- (uiprivTableCellView *)uiprivMakeCellView +{ + uiprivTableCellView *cv; + + cv = [[uiprivTextImageCheckboxTableCellView alloc] initWithFrame:NSZeroRect params:&(self->params)]; + [cv setIdentifier:[self identifier]]; + return cv; +} + +@end + +@interface uiprivProgressBarTableCellView : uiprivTableCellView { + uiTable *t; + uiTableModel *m; + NSProgressIndicator *p; + int modelColumn; +} +- (id)initWithFrame:(NSRect)r table:(uiTable *)table model:(uiTableModel *)model modelColumn:(int)mc; +@end + +@implementation uiprivProgressBarTableCellView + +- (id)initWithFrame:(NSRect)r table:(uiTable *)table model:(uiTableModel *)model modelColumn:(int)mc +{ + self = [super initWithFrame:r]; + if (self) { + self->t = table; + self->m = model; + self->modelColumn = mc; + + self->p = [[NSProgressIndicator alloc] initWithFrame:NSZeroRect]; + [self->p setControlSize:NSRegularControlSize]; + [self->p setBezeled:YES]; + [self->p setStyle:NSProgressIndicatorBarStyle]; + [self->p setTranslatesAutoresizingMaskIntoConstraints:NO]; + [self addSubview:self->p]; + + // TODO set hugging and compression resistance properly + [self addConstraint:uiprivMkConstraint(self, NSLayoutAttributeLeading, + NSLayoutRelationEqual, + self->p, NSLayoutAttributeLeading, + 1, -progressBarColumnLeading, + @"uiTable cell progressbar leading constraint")]; + [self addConstraint:uiprivMkConstraint(self, NSLayoutAttributeTop, + NSLayoutRelationEqual, + self->p, NSLayoutAttributeTop, + 1, 0, + @"uiTable cell progressbar top constraint")]; + [self addConstraint:uiprivMkConstraint(self, NSLayoutAttributeTrailing, + NSLayoutRelationEqual, + self->p, NSLayoutAttributeTrailing, + 1, progressBarColumnTrailing, + @"uiTable cell progressbar trailing constraint")]; + [self addConstraint:uiprivMkConstraint(self, NSLayoutAttributeBottom, + NSLayoutRelationEqual, + self->p, NSLayoutAttributeBottom, + 1, 0, + @"uiTable cell progressbar bottom constraint")]; + } + return self; +} + +- (void)dealloc +{ + [self->p release]; + self->p = nil; + [super dealloc]; +} + +- (void)uiprivUpdate:(NSInteger)row +{ + uiTableValue *value; + int progress; + + value = uiprivTableModelCellValue(self->m, row, self->modelColumn); + progress = uiTableValueInt(value); + uiFreeTableValue(value); + if (progress == -1) { + [self->p setIndeterminate:YES]; + [self->p startAnimation:self->p]; + } else if (progress == 100) { + [self->p setIndeterminate:NO]; + [self->p setMaxValue:101]; + [self->p setDoubleValue:101]; + [self->p setDoubleValue:100]; + [self->p setMaxValue:100]; + } else { + [self->p setIndeterminate:NO]; + [self->p setDoubleValue:(progress + 1)]; + [self->p setDoubleValue:progress]; + } +} + +@end + +@interface uiprivProgressBarTableColumn : uiprivTableColumn { + uiTable *t; + // TODO remove the need for this given t (or make t not require m, one of the two) + uiTableModel *m; + int modelColumn; +} +- (id)initWithIdentifier:(NSString *)ident table:(uiTable *)table model:(uiTableModel *)model modelColumn:(int)mc; +@end + +@implementation uiprivProgressBarTableColumn + +- (id)initWithIdentifier:(NSString *)ident table:(uiTable *)table model:(uiTableModel *)model modelColumn:(int)mc +{ + self = [super initWithIdentifier:ident]; + if (self) { + self->t = table; + self->m = model; + self->modelColumn = mc; + } + return self; +} + +- (uiprivTableCellView *)uiprivMakeCellView +{ + uiprivTableCellView *cv; + + cv = [[uiprivProgressBarTableCellView alloc] initWithFrame:NSZeroRect table:self->t model:self->m modelColumn:self->modelColumn]; + [cv setIdentifier:[self identifier]]; + return cv; +} + +@end + +@interface uiprivButtonTableCellView : uiprivTableCellView { + uiTable *t; + uiTableModel *m; + NSButton *b; + int modelColumn; + int editableColumn; +} +- (id)initWithFrame:(NSRect)r table:(uiTable *)table model:(uiTableModel *)model modelColumn:(int)mc editableColumn:(int)ec; +- (IBAction)uiprivOnClicked:(id)sender; +@end + +@implementation uiprivButtonTableCellView + +- (id)initWithFrame:(NSRect)r table:(uiTable *)table model:(uiTableModel *)model modelColumn:(int)mc editableColumn:(int)ec +{ + self = [super initWithFrame:r]; + if (self) { + self->t = table; + self->m = model; + self->modelColumn = mc; + self->editableColumn = ec; + + self->b = [[NSButton alloc] initWithFrame:NSZeroRect]; + [self->b setButtonType:NSMomentaryPushInButton]; + [self->b setBordered:YES]; + [self->b setBezelStyle:NSRoundRectBezelStyle]; + uiDarwinSetControlFont(self->b, NSRegularControlSize); + [self->b setTarget:self]; + [self->b setAction:@selector(uiprivOnClicked:)]; + [self->b setTranslatesAutoresizingMaskIntoConstraints:NO]; + [self addSubview:self->b]; + + // TODO set hugging and compression resistance properly + [self addConstraint:uiprivMkConstraint(self, NSLayoutAttributeLeading, + NSLayoutRelationEqual, + self->b, NSLayoutAttributeLeading, + 1, -buttonColumnLeading, + @"uiTable cell button leading constraint")]; + [self addConstraint:uiprivMkConstraint(self, NSLayoutAttributeTop, + NSLayoutRelationEqual, + self->b, NSLayoutAttributeTop, + 1, 0, + @"uiTable cell button top constraint")]; + [self addConstraint:uiprivMkConstraint(self, NSLayoutAttributeTrailing, + NSLayoutRelationEqual, + self->b, NSLayoutAttributeTrailing, + 1, buttonColumnTrailing, + @"uiTable cell button trailing constraint")]; + [self addConstraint:uiprivMkConstraint(self, NSLayoutAttributeBottom, + NSLayoutRelationEqual, + self->b, NSLayoutAttributeBottom, + 1, 0, + @"uiTable cell button bottom constraint")]; + } + return self; +} + +- (void)dealloc +{ + [self->b release]; + self->b = nil; + [super dealloc]; +} + +- (void)uiprivUpdate:(NSInteger)row +{ + uiTableValue *value; + NSString *str; + + value = uiprivTableModelCellValue(self->m, row, self->modelColumn); + str = uiprivToNSString(uiTableValueString(value)); + uiFreeTableValue(value); + [self->b setTitle:str]; + + [self->b setEnabled:uiprivTableModelCellEditable(self->m, row, self->editableColumn)]; +} + +- (IBAction)uiprivOnClicked:(id)sender +{ + NSInteger row; + + row = [self->t->tv rowForView:self->b]; + uiprivTableModelSetCellValue(self->m, row, self->modelColumn, NULL); + // TODO document we DON'T update the cell after doing this + // TODO or decide what to do instead +} + +@end + +@interface uiprivButtonTableColumn : uiprivTableColumn { + uiTable *t; + uiTableModel *m; + int modelColumn; + int editableColumn; +} +- (id)initWithIdentifier:(NSString *)ident table:(uiTable *)table model:(uiTableModel *)model modelColumn:(int)mc editableColumn:(int)ec; +@end + +@implementation uiprivButtonTableColumn + +- (id)initWithIdentifier:(NSString *)ident table:(uiTable *)table model:(uiTableModel *)model modelColumn:(int)mc editableColumn:(int)ec +{ + self = [super initWithIdentifier:ident]; + if (self) { + self->t = table; + self->m = model; + self->modelColumn = mc; + self->editableColumn = ec; + } + return self; +} + +- (uiprivTableCellView *)uiprivMakeCellView +{ + uiprivTableCellView *cv; + + cv = [[uiprivButtonTableCellView alloc] initWithFrame:NSZeroRect table:self->t model:self->m modelColumn:self->modelColumn editableColumn:self->editableColumn]; + [cv setIdentifier:[self identifier]]; + return cv; +} + +@end + +void uiTableAppendTextColumn(uiTable *t, const char *name, int textModelColumn, int textEditableModelColumn, uiTableTextColumnOptionalParams *textParams) +{ + struct textColumnCreateParams p; + uiprivTableColumn *col; + NSString *str; + + memset(&p, 0, sizeof (struct textColumnCreateParams)); + p.t = t; + p.m = t->m; + + p.makeTextField = YES; + p.textModelColumn = textModelColumn; + p.textEditableModelColumn = textEditableModelColumn; + if (textParams != NULL) + p.textParams = *textParams; + else + p.textParams = uiprivDefaultTextColumnOptionalParams; + + str = [NSString stringWithUTF8String:name]; + col = [[uiprivTextImageCheckboxTableColumn alloc] initWithIdentifier:str params:&p]; + [col setTitle:str]; + [t->tv addTableColumn:col]; +} + +void uiTableAppendImageColumn(uiTable *t, const char *name, int imageModelColumn) +{ + struct textColumnCreateParams p; + uiprivTableColumn *col; + NSString *str; + + memset(&p, 0, sizeof (struct textColumnCreateParams)); + p.t = t; + p.m = t->m; + + p.makeImageView = YES; + p.imageModelColumn = imageModelColumn; + + str = [NSString stringWithUTF8String:name]; + col = [[uiprivTextImageCheckboxTableColumn alloc] initWithIdentifier:str params:&p]; + [col setTitle:str]; + [t->tv addTableColumn:col]; +} + +void uiTableAppendImageTextColumn(uiTable *t, const char *name, int imageModelColumn, int textModelColumn, int textEditableModelColumn, uiTableTextColumnOptionalParams *textParams) +{ + struct textColumnCreateParams p; + uiprivTableColumn *col; + NSString *str; + + memset(&p, 0, sizeof (struct textColumnCreateParams)); + p.t = t; + p.m = t->m; + + p.makeTextField = YES; + p.textModelColumn = textModelColumn; + p.textEditableModelColumn = textEditableModelColumn; + if (textParams != NULL) + p.textParams = *textParams; + else + p.textParams = uiprivDefaultTextColumnOptionalParams; + + p.makeImageView = YES; + p.imageModelColumn = imageModelColumn; + + str = [NSString stringWithUTF8String:name]; + col = [[uiprivTextImageCheckboxTableColumn alloc] initWithIdentifier:str params:&p]; + [col setTitle:str]; + [t->tv addTableColumn:col]; +} + +void uiTableAppendCheckboxColumn(uiTable *t, const char *name, int checkboxModelColumn, int checkboxEditableModelColumn) +{ + struct textColumnCreateParams p; + uiprivTableColumn *col; + NSString *str; + + memset(&p, 0, sizeof (struct textColumnCreateParams)); + p.t = t; + p.m = t->m; + + p.makeCheckbox = YES; + p.checkboxModelColumn = checkboxModelColumn; + p.checkboxEditableModelColumn = checkboxEditableModelColumn; + + str = [NSString stringWithUTF8String:name]; + col = [[uiprivTextImageCheckboxTableColumn alloc] initWithIdentifier:str params:&p]; + [col setTitle:str]; + [t->tv addTableColumn:col]; +} + +void uiTableAppendCheckboxTextColumn(uiTable *t, const char *name, int checkboxModelColumn, int checkboxEditableModelColumn, int textModelColumn, int textEditableModelColumn, uiTableTextColumnOptionalParams *textParams) +{ + struct textColumnCreateParams p; + uiprivTableColumn *col; + NSString *str; + + memset(&p, 0, sizeof (struct textColumnCreateParams)); + p.t = t; + p.m = t->m; + + p.makeTextField = YES; + p.textModelColumn = textModelColumn; + p.textEditableModelColumn = textEditableModelColumn; + if (textParams != NULL) + p.textParams = *textParams; + else + p.textParams = uiprivDefaultTextColumnOptionalParams; + + p.makeCheckbox = YES; + p.checkboxModelColumn = checkboxModelColumn; + p.checkboxEditableModelColumn = checkboxEditableModelColumn; + + str = [NSString stringWithUTF8String:name]; + col = [[uiprivTextImageCheckboxTableColumn alloc] initWithIdentifier:str params:&p]; + [col setTitle:str]; + [t->tv addTableColumn:col]; +} + +void uiTableAppendProgressBarColumn(uiTable *t, const char *name, int progressModelColumn) +{ + uiprivTableColumn *col; + NSString *str; + + str = [NSString stringWithUTF8String:name]; + col = [[uiprivProgressBarTableColumn alloc] initWithIdentifier:str table:t model:t->m modelColumn:progressModelColumn]; + [col setTitle:str]; + [t->tv addTableColumn:col]; +} + +void uiTableAppendButtonColumn(uiTable *t, const char *name, int buttonModelColumn, int buttonClickableModelColumn) +{ + uiprivTableColumn *col; + NSString *str; + + str = [NSString stringWithUTF8String:name]; + col = [[uiprivButtonTableColumn alloc] initWithIdentifier:str table:t model:t->m modelColumn:buttonModelColumn editableColumn:buttonClickableModelColumn]; + [col setTitle:str]; + [t->tv addTableColumn:col]; +} diff --git a/dep/libui/darwin/text.m b/dep/libui/darwin/text.m new file mode 100644 index 0000000..8efd36f --- /dev/null +++ b/dep/libui/darwin/text.m @@ -0,0 +1,24 @@ +// 10 april 2015 +#import "uipriv_darwin.h" + +char *uiDarwinNSStringToText(NSString *s) +{ + char *out; + + out = strdup([s UTF8String]); + if (out == NULL) { + fprintf(stderr, "memory exhausted in uiDarwinNSStringToText()\n"); + abort(); + } + return out; +} + +void uiFreeText(char *s) +{ + free(s); +} + +int uiprivStricmp(const char *a, const char *b) +{ + return strcasecmp(a, b); +} diff --git a/dep/libui/darwin/uipriv_darwin.h b/dep/libui/darwin/uipriv_darwin.h new file mode 100644 index 0000000..5d50f62 --- /dev/null +++ b/dep/libui/darwin/uipriv_darwin.h @@ -0,0 +1,163 @@ +// 6 january 2015 +// note: as of OS X Sierra, the -mmacosx-version-min compiler options governs deprecation warnings; keep these around anyway just in case +#define MAC_OS_X_VERSION_MIN_REQUIRED MAC_OS_X_VERSION_10_8 +#define MAC_OS_X_VERSION_MAX_ALLOWED MAC_OS_X_VERSION_10_8 +#import +#import // see future.m +#import "../ui.h" +#import "../ui_darwin.h" +#import "../common/uipriv.h" + +// TODO should we rename the uiprivMk things or not +// TODO what about renaming class wrapper functions that return the underlying class (like uiprivNewLabel()) + +#if __has_feature(objc_arc) +#error Sorry, libui cannot be compiled with ARC. +#endif + +#define uiprivToNSString(str) [NSString stringWithUTF8String:(str)] +#define uiprivFromNSString(str) [(str) UTF8String] + +// TODO find a better place for this +#ifndef NSAppKitVersionNumber10_9 +#define NSAppKitVersionNumber10_9 1265 +#endif + +// map.m +typedef struct uiprivMap uiprivMap; +extern uiprivMap *uiprivNewMap(void); +extern void uiprivMapDestroy(uiprivMap *m); +extern void *uiprivMapGet(uiprivMap *m, void *key); +extern void uiprivMapSet(uiprivMap *m, void *key, void *value); +extern void uiprivMapDelete(uiprivMap *m, void *key); +extern void uiprivMapWalk(uiprivMap *m, void (*f)(void *key, void *value)); +extern void uiprivMapReset(uiprivMap *m); + +// menu.m +@interface uiprivMenuManager : NSObject { + uiprivMap *items; + BOOL hasQuit; + BOOL hasPreferences; + BOOL hasAbout; +} +@property (strong) NSMenuItem *quitItem; +@property (strong) NSMenuItem *preferencesItem; +@property (strong) NSMenuItem *aboutItem; +// NSMenuValidation is only informal +- (BOOL)validateMenuItem:(NSMenuItem *)item; +- (NSMenu *)makeMenubar; +@end +extern void uiprivFinalizeMenus(void); +extern void uiprivUninitMenus(void); + +// main.m +@interface uiprivApplicationClass : NSApplication +@end +// this is needed because NSApp is of type id, confusing clang +#define uiprivNSApp() ((uiprivApplicationClass *) NSApp) +@interface uiprivAppDelegate : NSObject +@property (strong) uiprivMenuManager *menuManager; +@end +#define uiprivAppDelegate() ((uiprivAppDelegate *) [uiprivNSApp() delegate]) +typedef struct uiprivNextEventArgs uiprivNextEventArgs; +struct uiprivNextEventArgs { + NSEventMask mask; + NSDate *duration; + // LONGTERM no NSRunLoopMode? + NSString *mode; + BOOL dequeue; +}; +extern int uiprivMainStep(uiprivNextEventArgs *nea, BOOL (^interceptEvent)(NSEvent *)); + +// util.m +extern void uiprivDisableAutocorrect(NSTextView *); + +// entry.m +extern void uiprivFinishNewTextField(NSTextField *, BOOL); +extern NSTextField *uiprivNewEditableTextField(void); + +// window.m +@interface uiprivNSWindow : NSWindow +- (void)uiprivDoMove:(NSEvent *)initialEvent; +- (void)uiprivDoResize:(NSEvent *)initialEvent on:(uiWindowResizeEdge)edge; +@end +extern uiWindow *uiprivWindowFromNSWindow(NSWindow *); + +// alloc.m +extern NSMutableArray *uiprivDelegates; +extern void uiprivInitAlloc(void); +extern void uiprivUninitAlloc(void); + +// autolayout.m +extern NSLayoutConstraint *uiprivMkConstraint(id view1, NSLayoutAttribute attr1, NSLayoutRelation relation, id view2, NSLayoutAttribute attr2, CGFloat multiplier, CGFloat c, NSString *desc); +extern void uiprivJiggleViewLayout(NSView *view); +typedef struct uiprivSingleChildConstraints uiprivSingleChildConstraints; +struct uiprivSingleChildConstraints { + NSLayoutConstraint *leadingConstraint; + NSLayoutConstraint *topConstraint; + NSLayoutConstraint *trailingConstraintGreater; + NSLayoutConstraint *trailingConstraintEqual; + NSLayoutConstraint *bottomConstraintGreater; + NSLayoutConstraint *bottomConstraintEqual; +}; +extern void uiprivSingleChildConstraintsEstablish(uiprivSingleChildConstraints *c, NSView *contentView, NSView *childView, BOOL hugsTrailing, BOOL hugsBottom, int margined, NSString *desc); +extern void uiprivSingleChildConstraintsRemove(uiprivSingleChildConstraints *c, NSView *cv); +extern void uiprivSingleChildConstraintsSetMargined(uiprivSingleChildConstraints *c, int margined); + +// area.m +extern int uiprivSendAreaEvents(NSEvent *); + +// areaevents.m +extern BOOL uiprivFromKeycode(unsigned short keycode, uiAreaKeyEvent *ke); +extern BOOL uiprivKeycodeModifier(unsigned short keycode, uiModifiers *mod); + +// draw.m +extern uiDrawContext *uiprivDrawNewContext(CGContextRef, CGFloat); +extern void uiprivDrawFreeContext(uiDrawContext *); + +// fontbutton.m +extern BOOL uiprivFontButtonInhibitSendAction(SEL sel, id from, id to); +extern BOOL uiprivFontButtonOverrideTargetForAction(SEL sel, id from, id to, id *override); +extern void uiprivSetupFontPanel(void); + +// colorbutton.m +extern BOOL uiprivColorButtonInhibitSendAction(SEL sel, id from, id to); + +// scrollview.m +typedef struct uiprivScrollViewCreateParams uiprivScrollViewCreateParams; +struct uiprivScrollViewCreateParams { + // TODO MAYBE fix these identifiers + NSView *DocumentView; + NSColor *BackgroundColor; + BOOL DrawsBackground; + BOOL Bordered; + BOOL HScroll; + BOOL VScroll; +}; +typedef struct uiprivScrollViewData uiprivScrollViewData; +extern NSScrollView *uiprivMkScrollView(uiprivScrollViewCreateParams *p, uiprivScrollViewData **dout); +extern void uiprivScrollViewSetScrolling(NSScrollView *sv, uiprivScrollViewData *d, BOOL hscroll, BOOL vscroll); +extern void uiprivScrollViewFreeData(NSScrollView *sv, uiprivScrollViewData *d); + +// label.m +extern NSTextField *uiprivNewLabel(NSString *str); + +// image.m +extern NSImage *uiprivImageNSImage(uiImage *); + +// winmoveresize.m +extern void uiprivDoManualMove(NSWindow *w, NSEvent *initialEvent); +extern void uiprivDoManualResize(NSWindow *w, NSEvent *initialEvent, uiWindowResizeEdge edge); + +// future.m +extern CFStringRef *uiprivFUTURE_kCTFontOpenTypeFeatureTag; +extern CFStringRef *uiprivFUTURE_kCTFontOpenTypeFeatureValue; +extern CFStringRef *uiprivFUTURE_kCTBackgroundColorAttributeName; +extern void uiprivLoadFutures(void); +extern void uiprivFUTURE_NSLayoutConstraint_setIdentifier(NSLayoutConstraint *constraint, NSString *identifier); +extern BOOL uiprivFUTURE_NSWindow_performWindowDragWithEvent(NSWindow *w, NSEvent *initialEvent); + +// undocumented.m +extern CFStringRef uiprivUNDOC_kCTFontPreferredSubFamilyNameKey; +extern CFStringRef uiprivUNDOC_kCTFontPreferredFamilyNameKey; +extern void uiprivLoadUndocumented(void); diff --git a/dep/libui/darwin/undocumented.m b/dep/libui/darwin/undocumented.m new file mode 100644 index 0000000..a3984aa --- /dev/null +++ b/dep/libui/darwin/undocumented.m @@ -0,0 +1,31 @@ +// 3 november 2017 +#import "uipriv_darwin.h" + +// functions and constants FROM THE DEPTHS BELOW! +// note: for constants, dlsym() returns the address of the constant itself, as if we had done &constantName +// we also provide default values just in case + +// these values come from 10.12.6 +CFStringRef uiprivUNDOC_kCTFontPreferredSubFamilyNameKey = CFSTR("CTFontPreferredSubFamilyName"); +CFStringRef uiprivUNDOC_kCTFontPreferredFamilyNameKey = CFSTR("CTFontPreferredFamilyName"); + +// note that we treat any error as "the symbols aren't there" (and don't care if dlclose() failed) +void uiprivLoadUndocumented(void) +{ + void *handle; + CFStringRef *str; + + // dlsym() walks the dependency chain, so opening the current process should be sufficient + handle = dlopen(NULL, RTLD_LAZY); + if (handle == NULL) + return; +#define GET(var, fn) *((void **) (&var)) = dlsym(handle, #fn) + GET(str, kCTFontPreferredSubFamilyNameKey); +NSLog(@"get %p", str); + if (str != NULL) + uiprivUNDOC_kCTFontPreferredSubFamilyNameKey = *str; + GET(str, kCTFontPreferredFamilyNameKey); + if (str != NULL) + uiprivUNDOC_kCTFontPreferredFamilyNameKey = *str; + dlclose(handle); +} diff --git a/dep/libui/darwin/util.m b/dep/libui/darwin/util.m new file mode 100644 index 0000000..418d958 --- /dev/null +++ b/dep/libui/darwin/util.m @@ -0,0 +1,16 @@ +// 7 april 2015 +#import "uipriv_darwin.h" + +// LONGTERM do we really want to do this? make it an option? +// TODO figure out why we removed this from window.m +void uiprivDisableAutocorrect(NSTextView *tv) +{ + [tv setEnabledTextCheckingTypes:0]; + [tv setAutomaticDashSubstitutionEnabled:NO]; + // don't worry about automatic data detection; it won't change stringValue (thanks pretty_function in irc.freenode.net/#macdev) + [tv setAutomaticSpellingCorrectionEnabled:NO]; + [tv setAutomaticTextReplacementEnabled:NO]; + [tv setAutomaticQuoteSubstitutionEnabled:NO]; + [tv setAutomaticLinkDetectionEnabled:NO]; + [tv setSmartInsertDeleteEnabled:NO]; +} diff --git a/dep/libui/darwin/window.m b/dep/libui/darwin/window.m new file mode 100644 index 0000000..1a04820 --- /dev/null +++ b/dep/libui/darwin/window.m @@ -0,0 +1,407 @@ +// 15 august 2015 +#import "uipriv_darwin.h" + +#define defaultStyleMask (NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask) + +struct uiWindow { + uiDarwinControl c; + NSWindow *window; + uiControl *child; + int margined; + int (*onClosing)(uiWindow *, void *); + void *onClosingData; + uiprivSingleChildConstraints constraints; + void (*onContentSizeChanged)(uiWindow *, void *); + void *onContentSizeChangedData; + BOOL suppressSizeChanged; + int fullscreen; + int borderless; +}; + +@implementation uiprivNSWindow + +- (void)uiprivDoMove:(NSEvent *)initialEvent +{ + uiprivDoManualMove(self, initialEvent); +} + +- (void)uiprivDoResize:(NSEvent *)initialEvent on:(uiWindowResizeEdge)edge +{ + uiprivDoManualResize(self, initialEvent, edge); +} + +@end + +@interface windowDelegateClass : NSObject { + uiprivMap *windows; +} +- (BOOL)windowShouldClose:(id)sender; +- (void)windowDidResize:(NSNotification *)note; +- (void)windowDidEnterFullScreen:(NSNotification *)note; +- (void)windowDidExitFullScreen:(NSNotification *)note; +- (void)registerWindow:(uiWindow *)w; +- (void)unregisterWindow:(uiWindow *)w; +- (uiWindow *)lookupWindow:(NSWindow *)w; +@end + +@implementation windowDelegateClass + +- (id)init +{ + self = [super init]; + if (self) + self->windows = uiprivNewMap(); + return self; +} + +- (void)dealloc +{ + uiprivMapDestroy(self->windows); + [super dealloc]; +} + +- (BOOL)windowShouldClose:(id)sender +{ + uiWindow *w; + + w = [self lookupWindow:((NSWindow *) sender)]; + // w should not be NULL; we are only the delegate of registered windows + if ((*(w->onClosing))(w, w->onClosingData)) + uiControlDestroy(uiControl(w)); + return NO; +} + +- (void)windowDidResize:(NSNotification *)note +{ + uiWindow *w; + + w = [self lookupWindow:((NSWindow *) [note object])]; + if (!w->suppressSizeChanged) + (*(w->onContentSizeChanged))(w, w->onContentSizeChangedData); +} + +- (void)windowDidEnterFullScreen:(NSNotification *)note +{ + uiWindow *w; + + w = [self lookupWindow:((NSWindow *) [note object])]; + if (!w->suppressSizeChanged) + w->fullscreen = 1; +} + +- (void)windowDidExitFullScreen:(NSNotification *)note +{ + uiWindow *w; + + w = [self lookupWindow:((NSWindow *) [note object])]; + if (!w->suppressSizeChanged) + w->fullscreen = 0; +} + +- (void)registerWindow:(uiWindow *)w +{ + uiprivMapSet(self->windows, w->window, w); + [w->window setDelegate:self]; +} + +- (void)unregisterWindow:(uiWindow *)w +{ + [w->window setDelegate:nil]; + uiprivMapDelete(self->windows, w->window); +} + +- (uiWindow *)lookupWindow:(NSWindow *)w +{ + uiWindow *v; + + v = uiWindow(uiprivMapGet(self->windows, w)); + // this CAN (and IS ALLOWED TO) return NULL, just in case we're called with some OS X-provided window as the key window + return v; +} + +@end + +static windowDelegateClass *windowDelegate = nil; + +static void removeConstraints(uiWindow *w) +{ + NSView *cv; + + cv = [w->window contentView]; + uiprivSingleChildConstraintsRemove(&(w->constraints), cv); +} + +static void uiWindowDestroy(uiControl *c) +{ + uiWindow *w = uiWindow(c); + + // hide the window + [w->window orderOut:w->window]; + removeConstraints(w); + if (w->child != NULL) { + uiControlSetParent(w->child, NULL); + uiDarwinControlSetSuperview(uiDarwinControl(w->child), nil); + uiControlDestroy(w->child); + } + [windowDelegate unregisterWindow:w]; + [w->window release]; + uiFreeControl(uiControl(w)); +} + +uiDarwinControlDefaultHandle(uiWindow, window) + +uiControl *uiWindowParent(uiControl *c) +{ + return NULL; +} + +void uiWindowSetParent(uiControl *c, uiControl *parent) +{ + uiUserBugCannotSetParentOnToplevel("uiWindow"); +} + +static int uiWindowToplevel(uiControl *c) +{ + return 1; +} + +static int uiWindowVisible(uiControl *c) +{ + uiWindow *w = uiWindow(c); + + return [w->window isVisible]; +} + +static void uiWindowShow(uiControl *c) +{ + uiWindow *w = (uiWindow *) c; + + [w->window makeKeyAndOrderFront:w->window]; +} + +static void uiWindowHide(uiControl *c) +{ + uiWindow *w = (uiWindow *) c; + + [w->window orderOut:w->window]; +} + +uiDarwinControlDefaultEnabled(uiWindow, window) +uiDarwinControlDefaultEnable(uiWindow, window) +uiDarwinControlDefaultDisable(uiWindow, window) + +static void uiWindowSyncEnableState(uiDarwinControl *c, int enabled) +{ + uiWindow *w = uiWindow(c); + + if (uiDarwinShouldStopSyncEnableState(uiDarwinControl(w), enabled)) + return; + if (w->child != NULL) + uiDarwinControlSyncEnableState(uiDarwinControl(w->child), enabled); +} + +static void uiWindowSetSuperview(uiDarwinControl *c, NSView *superview) +{ + // TODO +} + +static void windowRelayout(uiWindow *w) +{ + NSView *childView; + NSView *contentView; + + removeConstraints(w); + if (w->child == NULL) + return; + childView = (NSView *) uiControlHandle(w->child); + contentView = [w->window contentView]; + uiprivSingleChildConstraintsEstablish(&(w->constraints), + contentView, childView, + uiDarwinControlHugsTrailingEdge(uiDarwinControl(w->child)), + uiDarwinControlHugsBottom(uiDarwinControl(w->child)), + w->margined, + @"uiWindow"); +} + +uiDarwinControlDefaultHugsTrailingEdge(uiWindow, window) +uiDarwinControlDefaultHugsBottom(uiWindow, window) + +static void uiWindowChildEdgeHuggingChanged(uiDarwinControl *c) +{ + uiWindow *w = uiWindow(c); + + windowRelayout(w); +} + +// TODO +uiDarwinControlDefaultHuggingPriority(uiWindow, window) +uiDarwinControlDefaultSetHuggingPriority(uiWindow, window) +// end TODO + +static void uiWindowChildVisibilityChanged(uiDarwinControl *c) +{ + uiWindow *w = uiWindow(c); + + windowRelayout(w); +} + +char *uiWindowTitle(uiWindow *w) +{ + return uiDarwinNSStringToText([w->window title]); +} + +void uiWindowSetTitle(uiWindow *w, const char *title) +{ + [w->window setTitle:uiprivToNSString(title)]; +} + +void uiWindowContentSize(uiWindow *w, int *width, int *height) +{ + NSRect r; + + r = [w->window contentRectForFrameRect:[w->window frame]]; + *width = r.size.width; + *height = r.size.height; +} + +void uiWindowSetContentSize(uiWindow *w, int width, int height) +{ + w->suppressSizeChanged = YES; + [w->window setContentSize:NSMakeSize(width, height)]; + w->suppressSizeChanged = NO; +} + +int uiWindowFullscreen(uiWindow *w) +{ + return w->fullscreen; +} + +void uiWindowSetFullscreen(uiWindow *w, int fullscreen) +{ + if (w->fullscreen && fullscreen) + return; + if (!w->fullscreen && !fullscreen) + return; + w->fullscreen = fullscreen; + if (w->fullscreen && w->borderless) // borderless doesn't play nice with fullscreen; don't toggle while borderless + return; + w->suppressSizeChanged = YES; + [w->window toggleFullScreen:w->window]; + w->suppressSizeChanged = NO; + if (!w->fullscreen && w->borderless) // borderless doesn't play nice with fullscreen; restore borderless after removing + [w->window setStyleMask:NSBorderlessWindowMask]; +} + +void uiWindowOnContentSizeChanged(uiWindow *w, void (*f)(uiWindow *, void *), void *data) +{ + w->onContentSizeChanged = f; + w->onContentSizeChangedData = data; +} + +void uiWindowOnClosing(uiWindow *w, int (*f)(uiWindow *, void *), void *data) +{ + w->onClosing = f; + w->onClosingData = data; +} + +int uiWindowBorderless(uiWindow *w) +{ + return w->borderless; +} + +void uiWindowSetBorderless(uiWindow *w, int borderless) +{ + w->borderless = borderless; + if (w->borderless) { + // borderless doesn't play nice with fullscreen; wait for later + if (!w->fullscreen) + [w->window setStyleMask:NSBorderlessWindowMask]; + } else { + [w->window setStyleMask:defaultStyleMask]; + // borderless doesn't play nice with fullscreen; restore state + if (w->fullscreen) { + w->suppressSizeChanged = YES; + [w->window toggleFullScreen:w->window]; + w->suppressSizeChanged = NO; + } + } +} + +void uiWindowSetChild(uiWindow *w, uiControl *child) +{ + NSView *childView; + + if (w->child != NULL) { + childView = (NSView *) uiControlHandle(w->child); + [childView removeFromSuperview]; + uiControlSetParent(w->child, NULL); + } + w->child = child; + if (w->child != NULL) { + uiControlSetParent(w->child, uiControl(w)); + childView = (NSView *) uiControlHandle(w->child); + uiDarwinControlSetSuperview(uiDarwinControl(w->child), [w->window contentView]); + uiDarwinControlSyncEnableState(uiDarwinControl(w->child), uiControlEnabledToUser(uiControl(w))); + } + windowRelayout(w); +} + +int uiWindowMargined(uiWindow *w) +{ + return w->margined; +} + +void uiWindowSetMargined(uiWindow *w, int margined) +{ + w->margined = margined; + uiprivSingleChildConstraintsSetMargined(&(w->constraints), w->margined); +} + +static int defaultOnClosing(uiWindow *w, void *data) +{ + return 0; +} + +static void defaultOnPositionContentSizeChanged(uiWindow *w, void *data) +{ + // do nothing +} + +uiWindow *uiNewWindow(const char *title, int width, int height, int hasMenubar) +{ + uiWindow *w; + + uiprivFinalizeMenus(); + + uiDarwinNewControl(uiWindow, w); + + w->window = [[uiprivNSWindow alloc] initWithContentRect:NSMakeRect(0, 0, (CGFloat) width, (CGFloat) height) + styleMask:defaultStyleMask + backing:NSBackingStoreBuffered + defer:YES]; + [w->window setTitle:uiprivToNSString(title)]; + + // do NOT release when closed + // we manually do this in uiWindowDestroy() above + [w->window setReleasedWhenClosed:NO]; + + if (windowDelegate == nil) { + windowDelegate = [[windowDelegateClass new] autorelease]; + [uiprivDelegates addObject:windowDelegate]; + } + [windowDelegate registerWindow:w]; + uiWindowOnClosing(w, defaultOnClosing, NULL); + uiWindowOnContentSizeChanged(w, defaultOnPositionContentSizeChanged, NULL); + + return w; +} + +// utility function for menus +uiWindow *uiprivWindowFromNSWindow(NSWindow *w) +{ + if (w == nil) + return NULL; + if (windowDelegate == nil) // no windows were created yet; we're called with some OS X-provided window + return NULL; + return [windowDelegate lookupWindow:w]; +} diff --git a/dep/libui/darwin/winmoveresize.m b/dep/libui/darwin/winmoveresize.m new file mode 100644 index 0000000..efb61ea --- /dev/null +++ b/dep/libui/darwin/winmoveresize.m @@ -0,0 +1,253 @@ +// 1 november 2016 +#import "uipriv_darwin.h" + +// TODO option while resizing resizes both opposing sides at once (thanks swillits in irc.freenode.net/#macdev for showing this to me); figure out how far back that behavior goes when we do implement it + +// because we are changing the window frame each time the mouse moves, the successive -[NSEvent locationInWindow]s cannot be meaningfully used together +// make sure they are all following some sort of standard to avoid this problem; the screen is the most obvious possibility since it requires only one conversion (the only one that a NSWindow provides) +static NSPoint makeIndependent(NSPoint p, NSWindow *w) +{ + NSRect r; + + r.origin = p; + // mikeash in irc.freenode.net/#macdev confirms both that any size will do and that we can safely ignore the resultant size + r.size = NSZeroSize; + return [w convertRectToScreen:r].origin; +} + +struct onMoveDragParams { + NSWindow *w; + // using the previous point causes weird issues like the mouse seeming to fall behind the window edge... so do this instead + // TODO will this make things like the menubar and dock easier too? + NSRect initialFrame; + NSPoint initialPoint; +}; + +void onMoveDrag(struct onMoveDragParams *p, NSEvent *e) +{ + NSPoint new; + NSRect frame; + CGFloat offx, offy; + + new = makeIndependent([e locationInWindow], p->w); + frame = p->initialFrame; + + offx = new.x - p->initialPoint.x; + offy = new.y - p->initialPoint.y; + frame.origin.x += offx; + frame.origin.y += offy; + + // TODO handle the menubar + // TODO wait the system does this for us already?! + + [p->w setFrameOrigin:frame.origin]; +} + +void uiprivDoManualMove(NSWindow *w, NSEvent *initialEvent) +{ + __block struct onMoveDragParams mdp; + uiprivNextEventArgs nea; + BOOL (^handleEvent)(NSEvent *e); + __block BOOL done; + + // 10.11 gives us a method to handle this for us + // use it if available; this lets us use the real OS dragging code, which means we can take advantage of OS features like Spaces + if (uiprivFUTURE_NSWindow_performWindowDragWithEvent(w, initialEvent)) + return; + + mdp.w = w; + mdp.initialFrame = [mdp.w frame]; + mdp.initialPoint = makeIndependent([initialEvent locationInWindow], mdp.w); + + nea.mask = NSLeftMouseDraggedMask | NSLeftMouseUpMask; + nea.duration = [NSDate distantFuture]; + nea.mode = NSEventTrackingRunLoopMode; // nextEventMatchingMask: docs suggest using this for manual mouse tracking + nea.dequeue = YES; + handleEvent = ^(NSEvent *e) { + if ([e type] == NSLeftMouseUp) { + done = YES; + return YES; // do not send + } + onMoveDrag(&mdp, e); + return YES; // do not send + }; + done = NO; + while (uiprivMainStep(&nea, handleEvent)) + if (done) + break; +} + +// see http://stackoverflow.com/a/40352996/3408572 +static void minMaxAutoLayoutSizes(NSWindow *w, NSSize *min, NSSize *max) +{ + NSLayoutConstraint *cw, *ch; + NSView *contentView; + NSRect prevFrame; + + // if adding these constraints causes the window to change size somehow, don't show it to the user and change it back afterwards + NSDisableScreenUpdates(); + prevFrame = [w frame]; + + // minimum: encourage the window to be as small as possible + contentView = [w contentView]; + cw = uiprivMkConstraint(contentView, NSLayoutAttributeWidth, + NSLayoutRelationEqual, + nil, NSLayoutAttributeNotAnAttribute, + 0, 0, + @"window minimum width finding constraint"); + [cw setPriority:NSLayoutPriorityDragThatCanResizeWindow]; + [contentView addConstraint:cw]; + ch = uiprivMkConstraint(contentView, NSLayoutAttributeHeight, + NSLayoutRelationEqual, + nil, NSLayoutAttributeNotAnAttribute, + 0, 0, + @"window minimum height finding constraint"); + [ch setPriority:NSLayoutPriorityDragThatCanResizeWindow]; + [contentView addConstraint:ch]; + *min = [contentView fittingSize]; + [contentView removeConstraint:cw]; + [contentView removeConstraint:ch]; + + // maximum: encourage the window to be as large as possible + contentView = [w contentView]; + cw = uiprivMkConstraint(contentView, NSLayoutAttributeWidth, + NSLayoutRelationEqual, + nil, NSLayoutAttributeNotAnAttribute, + 0, CGFLOAT_MAX, + @"window maximum width finding constraint"); + [cw setPriority:NSLayoutPriorityDragThatCanResizeWindow]; + [contentView addConstraint:cw]; + ch = uiprivMkConstraint(contentView, NSLayoutAttributeHeight, + NSLayoutRelationEqual, + nil, NSLayoutAttributeNotAnAttribute, + 0, CGFLOAT_MAX, + @"window maximum height finding constraint"); + [ch setPriority:NSLayoutPriorityDragThatCanResizeWindow]; + [contentView addConstraint:ch]; + *max = [contentView fittingSize]; + [contentView removeConstraint:cw]; + [contentView removeConstraint:ch]; + + [w setFrame:prevFrame display:YES]; // TODO really YES? + NSEnableScreenUpdates(); +} + +static void handleResizeLeft(NSRect *frame, NSPoint old, NSPoint new) +{ + frame->origin.x += new.x - old.x; + frame->size.width -= new.x - old.x; +} + +// TODO properly handle the menubar +// TODO wait, OS X does it for us?! +static void handleResizeTop(NSRect *frame, NSPoint old, NSPoint new) +{ + frame->size.height += new.y - old.y; +} + +static void handleResizeRight(NSRect *frame, NSPoint old, NSPoint new) +{ + frame->size.width += new.x - old.x; +} + + +// TODO properly handle the menubar +static void handleResizeBottom(NSRect *frame, NSPoint old, NSPoint new) +{ + frame->origin.y += new.y - old.y; + frame->size.height -= new.y - old.y; +} + +struct onResizeDragParams { + NSWindow *w; + // using the previous point causes weird issues like the mouse seeming to fall behind the window edge... so do this instead + // TODO will this make things like the menubar and dock easier too? + NSRect initialFrame; + NSPoint initialPoint; + uiWindowResizeEdge edge; + NSSize min; + NSSize max; +}; + +static void onResizeDrag(struct onResizeDragParams *p, NSEvent *e) +{ + NSPoint new; + NSRect frame; + + new = makeIndependent([e locationInWindow], p->w); + frame = p->initialFrame; + + // horizontal + switch (p->edge) { + case uiWindowResizeEdgeLeft: + case uiWindowResizeEdgeTopLeft: + case uiWindowResizeEdgeBottomLeft: + handleResizeLeft(&frame, p->initialPoint, new); + break; + case uiWindowResizeEdgeRight: + case uiWindowResizeEdgeTopRight: + case uiWindowResizeEdgeBottomRight: + handleResizeRight(&frame, p->initialPoint, new); + break; + } + // vertical + switch (p->edge) { + case uiWindowResizeEdgeTop: + case uiWindowResizeEdgeTopLeft: + case uiWindowResizeEdgeTopRight: + handleResizeTop(&frame, p->initialPoint, new); + break; + case uiWindowResizeEdgeBottom: + case uiWindowResizeEdgeBottomLeft: + case uiWindowResizeEdgeBottomRight: + handleResizeBottom(&frame, p->initialPoint, new); + break; + } + + // constrain + // TODO should we constrain against anything else as well? minMaxAutoLayoutSizes() already gives us nonnegative sizes, but... + if (frame.size.width < p->min.width) + frame.size.width = p->min.width; + if (frame.size.height < p->min.height) + frame.size.height = p->min.height; + // TODO > or >= ? + if (frame.size.width > p->max.width) + frame.size.width = p->max.width; + if (frame.size.height > p->max.height) + frame.size.height = p->max.height; + + [p->w setFrame:frame display:YES]; // and do reflect the new frame immediately +} + +// TODO do our events get fired with this? *should* they? +void uiprivDoManualResize(NSWindow *w, NSEvent *initialEvent, uiWindowResizeEdge edge) +{ + __block struct onResizeDragParams rdp; + uiprivNextEventArgs nea; + BOOL (^handleEvent)(NSEvent *e); + __block BOOL done; + + rdp.w = w; + rdp.initialFrame = [rdp.w frame]; + rdp.initialPoint = makeIndependent([initialEvent locationInWindow], rdp.w); + rdp.edge = edge; + // TODO what happens if these change during the loop? + minMaxAutoLayoutSizes(rdp.w, &(rdp.min), &(rdp.max)); + + nea.mask = NSLeftMouseDraggedMask | NSLeftMouseUpMask; + nea.duration = [NSDate distantFuture]; + nea.mode = NSEventTrackingRunLoopMode; // nextEventMatchingMask: docs suggest using this for manual mouse tracking + nea.dequeue = YES; + handleEvent = ^(NSEvent *e) { + if ([e type] == NSLeftMouseUp) { + done = YES; + return YES; // do not send + } + onResizeDrag(&rdp, e); + return YES; // do not send + }; + done = NO; + while (uiprivMainStep(&nea, handleEvent)) + if (done) + break; +} diff --git a/dep/libui/examples/controlgallery/darwin.png b/dep/libui/examples/controlgallery/darwin.png new file mode 100644 index 0000000..f61b54b Binary files /dev/null and b/dep/libui/examples/controlgallery/darwin.png differ diff --git a/dep/libui/examples/controlgallery/main.c b/dep/libui/examples/controlgallery/main.c new file mode 100644 index 0000000..c0d536c --- /dev/null +++ b/dep/libui/examples/controlgallery/main.c @@ -0,0 +1,540 @@ +// 2 september 2015 +#include +#include +#include "../../ui.h" + +static int onClosing(uiWindow *w, void *data) +{ + uiQuit(); + return 1; +} + +static int onShouldQuit(void *data) +{ + uiWindow *mainwin = uiWindow(data); + + uiControlDestroy(uiControl(mainwin)); + return 1; +} + +static uiControl *makeBasicControlsPage(void) +{ + uiBox *vbox; + uiBox *hbox; + uiGroup *group; + uiForm *entryForm; + + vbox = uiNewVerticalBox(); + uiBoxSetPadded(vbox, 1); + + hbox = uiNewHorizontalBox(); + uiBoxSetPadded(hbox, 1); + uiBoxAppend(vbox, uiControl(hbox), 0); + + uiBoxAppend(hbox, + uiControl(uiNewButton("Button")), + 0); + uiBoxAppend(hbox, + uiControl(uiNewCheckbox("Checkbox")), + 0); + + uiBoxAppend(vbox, + uiControl(uiNewLabel("This is a label. Right now, labels can only span one line.")), + 0); + + uiBoxAppend(vbox, + uiControl(uiNewHorizontalSeparator()), + 0); + + group = uiNewGroup("Entries"); + uiGroupSetMargined(group, 1); + uiBoxAppend(vbox, uiControl(group), 1); + + entryForm = uiNewForm(); + uiFormSetPadded(entryForm, 1); + uiGroupSetChild(group, uiControl(entryForm)); + + uiFormAppend(entryForm, + "Entry", + uiControl(uiNewEntry()), + 0); + uiFormAppend(entryForm, + "Password Entry", + uiControl(uiNewPasswordEntry()), + 0); + uiFormAppend(entryForm, + "Search Entry", + uiControl(uiNewSearchEntry()), + 0); + uiFormAppend(entryForm, + "Multiline Entry", + uiControl(uiNewMultilineEntry()), + 1); + uiFormAppend(entryForm, + "Multiline Entry No Wrap", + uiControl(uiNewNonWrappingMultilineEntry()), + 1); + + return uiControl(vbox); +} + +// TODO make these not global +static uiSpinbox *spinbox; +static uiSlider *slider; +static uiProgressBar *pbar; + +static void onSpinboxChanged(uiSpinbox *s, void *data) +{ + uiSliderSetValue(slider, uiSpinboxValue(s)); + uiProgressBarSetValue(pbar, uiSpinboxValue(s)); +} + +static void onSliderChanged(uiSlider *s, void *data) +{ + uiSpinboxSetValue(spinbox, uiSliderValue(s)); + uiProgressBarSetValue(pbar, uiSliderValue(s)); +} + +static uiControl *makeNumbersPage() +{ + uiBox *hbox; + uiGroup *group; + uiBox *vbox; + uiProgressBar *ip; + uiCombobox *cbox; + uiEditableCombobox *ecbox; + uiRadioButtons *rb; + + hbox = uiNewHorizontalBox(); + uiBoxSetPadded(hbox, 1); + + group = uiNewGroup("Numbers"); + uiGroupSetMargined(group, 1); + uiBoxAppend(hbox, uiControl(group), 1); + + vbox = uiNewVerticalBox(); + uiBoxSetPadded(vbox, 1); + uiGroupSetChild(group, uiControl(vbox)); + + spinbox = uiNewSpinbox(0, 100); + slider = uiNewSlider(0, 100); + pbar = uiNewProgressBar(); + uiSpinboxOnChanged(spinbox, onSpinboxChanged, NULL); + uiSliderOnChanged(slider, onSliderChanged, NULL); + uiBoxAppend(vbox, uiControl(spinbox), 0); + uiBoxAppend(vbox, uiControl(slider), 0); + uiBoxAppend(vbox, uiControl(pbar), 0); + + ip = uiNewProgressBar(); + uiProgressBarSetValue(ip, -1); + uiBoxAppend(vbox, uiControl(ip), 0); + + group = uiNewGroup("Lists"); + uiGroupSetMargined(group, 1); + uiBoxAppend(hbox, uiControl(group), 1); + + vbox = uiNewVerticalBox(); + uiBoxSetPadded(vbox, 1); + uiGroupSetChild(group, uiControl(vbox)); + + cbox = uiNewCombobox(); + uiComboboxAppend(cbox, "Combobox Item 1"); + uiComboboxAppend(cbox, "Combobox Item 2"); + uiComboboxAppend(cbox, "Combobox Item 3"); + uiBoxAppend(vbox, uiControl(cbox), 0); + + ecbox = uiNewEditableCombobox(); + uiEditableComboboxAppend(ecbox, "Editable Item 1"); + uiEditableComboboxAppend(ecbox, "Editable Item 2"); + uiEditableComboboxAppend(ecbox, "Editable Item 3"); + uiBoxAppend(vbox, uiControl(ecbox), 0); + + rb = uiNewRadioButtons(); + uiRadioButtonsAppend(rb, "Radio Button 1"); + uiRadioButtonsAppend(rb, "Radio Button 2"); + uiRadioButtonsAppend(rb, "Radio Button 3"); + uiBoxAppend(vbox, uiControl(rb), 0); + + return uiControl(hbox); +} + +// TODO make this not global +static uiWindow *mainwin; + +static void onOpenFileClicked(uiButton *b, void *data) +{ + uiEntry *entry = uiEntry(data); + char *filename; + + filename = uiOpenFile(mainwin); + if (filename == NULL) { + uiEntrySetText(entry, "(cancelled)"); + return; + } + uiEntrySetText(entry, filename); + uiFreeText(filename); +} + +static void onSaveFileClicked(uiButton *b, void *data) +{ + uiEntry *entry = uiEntry(data); + char *filename; + + filename = uiSaveFile(mainwin); + if (filename == NULL) { + uiEntrySetText(entry, "(cancelled)"); + return; + } + uiEntrySetText(entry, filename); + uiFreeText(filename); +} + +static void onMsgBoxClicked(uiButton *b, void *data) +{ + uiMsgBox(mainwin, + "This is a normal message box.", + "More detailed information can be shown here."); +} + +static void onMsgBoxErrorClicked(uiButton *b, void *data) +{ + uiMsgBoxError(mainwin, + "This message box describes an error.", + "More detailed information can be shown here."); +} + +static uiControl *makeDataChoosersPage(void) +{ + uiBox *hbox; + uiBox *vbox; + uiGrid *grid; + uiButton *button; + uiEntry *entry; + uiGrid *msggrid; + + hbox = uiNewHorizontalBox(); + uiBoxSetPadded(hbox, 1); + + vbox = uiNewVerticalBox(); + uiBoxSetPadded(vbox, 1); + uiBoxAppend(hbox, uiControl(vbox), 0); + + uiBoxAppend(vbox, + uiControl(uiNewDatePicker()), + 0); + uiBoxAppend(vbox, + uiControl(uiNewTimePicker()), + 0); + uiBoxAppend(vbox, + uiControl(uiNewDateTimePicker()), + 0); + + uiBoxAppend(vbox, + uiControl(uiNewFontButton()), + 0); + uiBoxAppend(vbox, + uiControl(uiNewColorButton()), + 0); + + uiBoxAppend(hbox, + uiControl(uiNewVerticalSeparator()), + 0); + + vbox = uiNewVerticalBox(); + uiBoxSetPadded(vbox, 1); + uiBoxAppend(hbox, uiControl(vbox), 1); + + grid = uiNewGrid(); + uiGridSetPadded(grid, 1); + uiBoxAppend(vbox, uiControl(grid), 0); + + button = uiNewButton("Open File"); + entry = uiNewEntry(); + uiEntrySetReadOnly(entry, 1); + uiButtonOnClicked(button, onOpenFileClicked, entry); + uiGridAppend(grid, uiControl(button), + 0, 0, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + uiGridAppend(grid, uiControl(entry), + 1, 0, 1, 1, + 1, uiAlignFill, 0, uiAlignFill); + + button = uiNewButton("Save File"); + entry = uiNewEntry(); + uiEntrySetReadOnly(entry, 1); + uiButtonOnClicked(button, onSaveFileClicked, entry); + uiGridAppend(grid, uiControl(button), + 0, 1, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + uiGridAppend(grid, uiControl(entry), + 1, 1, 1, 1, + 1, uiAlignFill, 0, uiAlignFill); + + msggrid = uiNewGrid(); + uiGridSetPadded(msggrid, 1); + uiGridAppend(grid, uiControl(msggrid), + 0, 2, 2, 1, + 0, uiAlignCenter, 0, uiAlignStart); + + button = uiNewButton("Message Box"); + uiButtonOnClicked(button, onMsgBoxClicked, NULL); + uiGridAppend(msggrid, uiControl(button), + 0, 0, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + button = uiNewButton("Error Box"); + uiButtonOnClicked(button, onMsgBoxErrorClicked, NULL); + uiGridAppend(msggrid, uiControl(button), + 1, 0, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + + return uiControl(hbox); +} + +int main(void) +{ + uiInitOptions options; + const char *err; + uiTab *tab; + + memset(&options, 0, sizeof (uiInitOptions)); + err = uiInit(&options); + if (err != NULL) { + fprintf(stderr, "error initializing libui: %s", err); + uiFreeInitError(err); + return 1; + } + + mainwin = uiNewWindow("libui Control Gallery", 640, 480, 1); + uiWindowOnClosing(mainwin, onClosing, NULL); + uiOnShouldQuit(onShouldQuit, mainwin); + + tab = uiNewTab(); + uiWindowSetChild(mainwin, uiControl(tab)); + uiWindowSetMargined(mainwin, 1); + + uiTabAppend(tab, "Basic Controls", makeBasicControlsPage()); + uiTabSetMargined(tab, 0, 1); + + uiTabAppend(tab, "Numbers and Lists", makeNumbersPage()); + uiTabSetMargined(tab, 1, 1); + + uiTabAppend(tab, "Data Choosers", makeDataChoosersPage()); + uiTabSetMargined(tab, 2, 1); + + uiControlShow(uiControl(mainwin)); + uiMain(); + return 0; +} + +#if 0 + +static void openClicked(uiMenuItem *item, uiWindow *w, void *data) +{ + char *filename; + + filename = uiOpenFile(mainwin); + if (filename == NULL) { + uiMsgBoxError(mainwin, "No file selected", "Don't be alarmed!"); + return; + } + uiMsgBox(mainwin, "File selected", filename); + uiFreeText(filename); +} + +static void saveClicked(uiMenuItem *item, uiWindow *w, void *data) +{ + char *filename; + + filename = uiSaveFile(mainwin); + if (filename == NULL) { + uiMsgBoxError(mainwin, "No file selected", "Don't be alarmed!"); + return; + } + uiMsgBox(mainwin, "File selected (don't worry, it's still there)", filename); + uiFreeText(filename); +} + +static uiSpinbox *spinbox; +static uiSlider *slider; +static uiProgressBar *progressbar; + +static void update(int value) +{ + uiSpinboxSetValue(spinbox, value); + uiSliderSetValue(slider, value); + uiProgressBarSetValue(progressbar, value); +} + +static void onSpinboxChanged(uiSpinbox *s, void *data) +{ + update(uiSpinboxValue(spinbox)); +} + +static void onSliderChanged(uiSlider *s, void *data) +{ + update(uiSliderValue(slider)); +} + +int main(void) +{ + uiInitOptions o; + const char *err; + uiMenu *menu; + uiMenuItem *item; + uiBox *box; + uiBox *hbox; + uiGroup *group; + uiBox *inner; + uiBox *inner2; + uiEntry *entry; + uiCombobox *cbox; + uiEditableCombobox *ecbox; + uiRadioButtons *rb; + uiTab *tab; + + memset(&o, 0, sizeof (uiInitOptions)); + err = uiInit(&o); + if (err != NULL) { + fprintf(stderr, "error initializing ui: %s\n", err); + uiFreeInitError(err); + return 1; + } + + menu = uiNewMenu("File"); + item = uiMenuAppendItem(menu, "Open"); + uiMenuItemOnClicked(item, openClicked, NULL); + item = uiMenuAppendItem(menu, "Save"); + uiMenuItemOnClicked(item, saveClicked, NULL); + item = uiMenuAppendQuitItem(menu); + uiOnShouldQuit(shouldQuit, NULL); + + menu = uiNewMenu("Edit"); + item = uiMenuAppendCheckItem(menu, "Checkable Item"); + uiMenuAppendSeparator(menu); + item = uiMenuAppendItem(menu, "Disabled Item"); + uiMenuItemDisable(item); + item = uiMenuAppendPreferencesItem(menu); + + menu = uiNewMenu("Help"); + item = uiMenuAppendItem(menu, "Help"); + item = uiMenuAppendAboutItem(menu); + + mainwin = uiNewWindow("libui Control Gallery", 640, 480, 1); + uiWindowSetMargined(mainwin, 1); + uiWindowOnClosing(mainwin, onClosing, NULL); + + box = uiNewVerticalBox(); + uiBoxSetPadded(box, 1); + uiWindowSetChild(mainwin, uiControl(box)); + + hbox = uiNewHorizontalBox(); + uiBoxSetPadded(hbox, 1); + uiBoxAppend(box, uiControl(hbox), 1); + + group = uiNewGroup("Basic Controls"); + uiGroupSetMargined(group, 1); + uiBoxAppend(hbox, uiControl(group), 0); + + inner = uiNewVerticalBox(); + uiBoxSetPadded(inner, 1); + uiGroupSetChild(group, uiControl(inner)); + + uiBoxAppend(inner, + uiControl(uiNewButton("Button")), + 0); + uiBoxAppend(inner, + uiControl(uiNewCheckbox("Checkbox")), + 0); + entry = uiNewEntry(); + uiEntrySetText(entry, "Entry"); + uiBoxAppend(inner, + uiControl(entry), + 0); + uiBoxAppend(inner, + uiControl(uiNewLabel("Label")), + 0); + + uiBoxAppend(inner, + uiControl(uiNewHorizontalSeparator()), + 0); + + uiBoxAppend(inner, + uiControl(uiNewDatePicker()), + 0); + uiBoxAppend(inner, + uiControl(uiNewTimePicker()), + 0); + uiBoxAppend(inner, + uiControl(uiNewDateTimePicker()), + 0); + + uiBoxAppend(inner, + uiControl(uiNewFontButton()), + 0); + + uiBoxAppend(inner, + uiControl(uiNewColorButton()), + 0); + + inner2 = uiNewVerticalBox(); + uiBoxSetPadded(inner2, 1); + uiBoxAppend(hbox, uiControl(inner2), 1); + + group = uiNewGroup("Numbers"); + uiGroupSetMargined(group, 1); + uiBoxAppend(inner2, uiControl(group), 0); + + inner = uiNewVerticalBox(); + uiBoxSetPadded(inner, 1); + uiGroupSetChild(group, uiControl(inner)); + + spinbox = uiNewSpinbox(0, 100); + uiSpinboxOnChanged(spinbox, onSpinboxChanged, NULL); + uiBoxAppend(inner, uiControl(spinbox), 0); + + slider = uiNewSlider(0, 100); + uiSliderOnChanged(slider, onSliderChanged, NULL); + uiBoxAppend(inner, uiControl(slider), 0); + + progressbar = uiNewProgressBar(); + uiBoxAppend(inner, uiControl(progressbar), 0); + + group = uiNewGroup("Lists"); + uiGroupSetMargined(group, 1); + uiBoxAppend(inner2, uiControl(group), 0); + + inner = uiNewVerticalBox(); + uiBoxSetPadded(inner, 1); + uiGroupSetChild(group, uiControl(inner)); + + cbox = uiNewCombobox(); + uiComboboxAppend(cbox, "Combobox Item 1"); + uiComboboxAppend(cbox, "Combobox Item 2"); + uiComboboxAppend(cbox, "Combobox Item 3"); + uiBoxAppend(inner, uiControl(cbox), 0); + + ecbox = uiNewEditableCombobox(); + uiEditableComboboxAppend(ecbox, "Editable Item 1"); + uiEditableComboboxAppend(ecbox, "Editable Item 2"); + uiEditableComboboxAppend(ecbox, "Editable Item 3"); + uiBoxAppend(inner, uiControl(ecbox), 0); + + rb = uiNewRadioButtons(); + uiRadioButtonsAppend(rb, "Radio Button 1"); + uiRadioButtonsAppend(rb, "Radio Button 2"); + uiRadioButtonsAppend(rb, "Radio Button 3"); + uiBoxAppend(inner, uiControl(rb), 1); + + tab = uiNewTab(); + uiTabAppend(tab, "Page 1", uiControl(uiNewHorizontalBox())); + uiTabAppend(tab, "Page 2", uiControl(uiNewHorizontalBox())); + uiTabAppend(tab, "Page 3", uiControl(uiNewHorizontalBox())); + uiBoxAppend(inner2, uiControl(tab), 1); + + uiControlShow(uiControl(mainwin)); + uiMain(); + uiUninit(); + return 0; +} + +#endif diff --git a/dep/libui/examples/controlgallery/unix.png b/dep/libui/examples/controlgallery/unix.png new file mode 100644 index 0000000..0c58d09 Binary files /dev/null and b/dep/libui/examples/controlgallery/unix.png differ diff --git a/dep/libui/examples/controlgallery/windows.png b/dep/libui/examples/controlgallery/windows.png new file mode 100755 index 0000000..4be832f Binary files /dev/null and b/dep/libui/examples/controlgallery/windows.png differ diff --git a/dep/libui/examples/cpp-multithread/main.cpp b/dep/libui/examples/cpp-multithread/main.cpp new file mode 100644 index 0000000..f97bc6f --- /dev/null +++ b/dep/libui/examples/cpp-multithread/main.cpp @@ -0,0 +1,92 @@ +// 6 december 2015 +#include +#include +#include +#include +#include +#include +#include +#include "../../ui.h" +using namespace std; + +uiMultilineEntry *e; +condition_variable cv; +mutex m; +unique_lock ourlock(m); +thread *timeThread; + +void sayTime(void *data) +{ + char *s = (char *) data; + + uiMultilineEntryAppend(e, s); + delete s; +} + +void threadproc(void) +{ + ourlock.lock(); + while (cv.wait_for(ourlock, chrono::seconds(1)) == cv_status::timeout) { + time_t t; + char *base; + char *s; + + t = time(NULL); + base = ctime(&t); + s = new char[strlen(base) + 1]; + strcpy(s, base); + uiQueueMain(sayTime, s); + } +} + +int onClosing(uiWindow *w, void *data) +{ + cv.notify_all(); + // C++ throws a hissy fit if you don't do this + // we might as well, to ensure no uiQueueMain() gets in after uiQuit() + timeThread->join(); + uiQuit(); + return 1; +} + +void saySomething(uiButton *b, void *data) +{ + uiMultilineEntryAppend(e, "Saying something\n"); +} + +int main(void) +{ + uiInitOptions o; + uiWindow *w; + uiBox *b; + uiButton *btn; + + memset(&o, 0, sizeof (uiInitOptions)); + if (uiInit(&o) != NULL) + abort(); + + w = uiNewWindow("Hello", 320, 240, 0); + uiWindowSetMargined(w, 1); + + b = uiNewVerticalBox(); + uiBoxSetPadded(b, 1); + uiWindowSetChild(w, uiControl(b)); + + e = uiNewMultilineEntry(); + uiMultilineEntrySetReadOnly(e, 1); + + btn = uiNewButton("Say Something"); + uiButtonOnClicked(btn, saySomething, NULL); + uiBoxAppend(b, uiControl(btn), 0); + + uiBoxAppend(b, uiControl(e), 1); + + // timeThread needs to lock ourlock itself - see http://stackoverflow.com/a/34121629/3408572 + ourlock.unlock(); + timeThread = new thread(threadproc); + + uiWindowOnClosing(w, onClosing, NULL); + uiControlShow(uiControl(w)); + uiMain(); + return 0; +} diff --git a/dep/libui/examples/datetime/main.c b/dep/libui/examples/datetime/main.c new file mode 100644 index 0000000..5f10eb0 --- /dev/null +++ b/dep/libui/examples/datetime/main.c @@ -0,0 +1,128 @@ +#include +#include +#include +#include +#include "../../ui.h" + +uiDateTimePicker *dtboth, *dtdate, *dttime; + +const char *timeFormat(uiDateTimePicker *d) +{ + const char *fmt; + + if (d == dtboth) + fmt = "%c"; + else if (d == dtdate) + fmt = "%x"; + else if (d == dttime) + fmt = "%X"; + else + fmt = ""; + return fmt; +} + +void onChanged(uiDateTimePicker *d, void *data) +{ + struct tm time; + char buf[64]; + + uiDateTimePickerTime(d, &time); + strftime(buf, sizeof (buf), timeFormat(d), &time); + uiLabelSetText(uiLabel(data), buf); +} + +void onClicked(uiButton *b, void *data) +{ + intptr_t now; + time_t t; + struct tm tmbuf; + + now = (intptr_t) data; + t = 0; + if (now) + t = time(NULL); + tmbuf = *localtime(&t); + + if (now) { + uiDateTimePickerSetTime(dtdate, &tmbuf); + uiDateTimePickerSetTime(dttime, &tmbuf); + } else + uiDateTimePickerSetTime(dtboth, &tmbuf); +} + +int onClosing(uiWindow *w, void *data) +{ + uiQuit(); + return 1; +} + +int main(void) +{ + uiInitOptions o; + const char *err; + uiWindow *w; + uiGrid *g; + uiLabel *l; + uiButton *b; + + memset(&o, 0, sizeof (uiInitOptions)); + err = uiInit(&o); + if (err != NULL) { + fprintf(stderr, "error initializing ui: %s\n", err); + uiFreeInitError(err); + return 1; + } + + w = uiNewWindow("Date / Time", 320, 240, 0); + uiWindowSetMargined(w, 1); + + g = uiNewGrid(); + uiGridSetPadded(g, 1); + uiWindowSetChild(w, uiControl(g)); + + dtboth = uiNewDateTimePicker(); + dtdate = uiNewDatePicker(); + dttime = uiNewTimePicker(); + + uiGridAppend(g, uiControl(dtboth), + 0, 0, 2, 1, + 1, uiAlignFill, 0, uiAlignFill); + uiGridAppend(g, uiControl(dtdate), + 0, 1, 1, 1, + 1, uiAlignFill, 0, uiAlignFill); + uiGridAppend(g, uiControl(dttime), + 1, 1, 1, 1, + 1, uiAlignFill, 0, uiAlignFill); + + l = uiNewLabel(""); + uiGridAppend(g, uiControl(l), + 0, 2, 2, 1, + 1, uiAlignCenter, 0, uiAlignFill); + uiDateTimePickerOnChanged(dtboth, onChanged, l); + l = uiNewLabel(""); + uiGridAppend(g, uiControl(l), + 0, 3, 1, 1, + 1, uiAlignCenter, 0, uiAlignFill); + uiDateTimePickerOnChanged(dtdate, onChanged, l); + l = uiNewLabel(""); + uiGridAppend(g, uiControl(l), + 1, 3, 1, 1, + 1, uiAlignCenter, 0, uiAlignFill); + uiDateTimePickerOnChanged(dttime, onChanged, l); + + b = uiNewButton("Now"); + uiButtonOnClicked(b, onClicked, (void *) 1); + uiGridAppend(g, uiControl(b), + 0, 4, 1, 1, + 1, uiAlignFill, 1, uiAlignEnd); + b = uiNewButton("Unix epoch"); + uiButtonOnClicked(b, onClicked, (void *) 0); + uiGridAppend(g, uiControl(b), + 1, 4, 1, 1, + 1, uiAlignFill, 1, uiAlignEnd); + + uiWindowOnClosing(w, onClosing, NULL); + uiControlShow(uiControl(w)); + uiMain(); + return 0; +} diff --git a/dep/libui/examples/drawtext/main.c b/dep/libui/examples/drawtext/main.c new file mode 100644 index 0000000..d94d257 --- /dev/null +++ b/dep/libui/examples/drawtext/main.c @@ -0,0 +1,219 @@ +// 10 march 2018 +#include +#include +#include "../../ui.h" + +uiWindow *mainwin; +uiArea *area; +uiAreaHandler handler; +uiFontButton *fontButton; +uiCombobox *alignment; + +uiAttributedString *attrstr; + +static void appendWithAttribute(const char *what, uiAttribute *attr, uiAttribute *attr2) +{ + size_t start, end; + + start = uiAttributedStringLen(attrstr); + end = start + strlen(what); + uiAttributedStringAppendUnattributed(attrstr, what); + uiAttributedStringSetAttribute(attrstr, attr, start, end); + if (attr2 != NULL) + uiAttributedStringSetAttribute(attrstr, attr2, start, end); +} + +static void makeAttributedString(void) +{ + uiAttribute *attr, *attr2; + uiOpenTypeFeatures *otf; + + attrstr = uiNewAttributedString( + "Drawing strings with libui is done with the uiAttributedString and uiDrawTextLayout objects.\n" + "uiAttributedString lets you have a variety of attributes: "); + + attr = uiNewFamilyAttribute("Courier New"); + appendWithAttribute("font family", attr, NULL); + uiAttributedStringAppendUnattributed(attrstr, ", "); + + attr = uiNewSizeAttribute(18); + appendWithAttribute("font size", attr, NULL); + uiAttributedStringAppendUnattributed(attrstr, ", "); + + attr = uiNewWeightAttribute(uiTextWeightBold); + appendWithAttribute("font weight", attr, NULL); + uiAttributedStringAppendUnattributed(attrstr, ", "); + + attr = uiNewItalicAttribute(uiTextItalicItalic); + appendWithAttribute("font italicness", attr, NULL); + uiAttributedStringAppendUnattributed(attrstr, ", "); + + attr = uiNewStretchAttribute(uiTextStretchCondensed); + appendWithAttribute("font stretch", attr, NULL); + uiAttributedStringAppendUnattributed(attrstr, ", "); + + attr = uiNewColorAttribute(0.75, 0.25, 0.5, 0.75); + appendWithAttribute("text color", attr, NULL); + uiAttributedStringAppendUnattributed(attrstr, ", "); + + attr = uiNewBackgroundAttribute(0.5, 0.5, 0.25, 0.5); + appendWithAttribute("text background color", attr, NULL); + uiAttributedStringAppendUnattributed(attrstr, ", "); + + + attr = uiNewUnderlineAttribute(uiUnderlineSingle); + appendWithAttribute("underline style", attr, NULL); + uiAttributedStringAppendUnattributed(attrstr, ", "); + + uiAttributedStringAppendUnattributed(attrstr, "and "); + attr = uiNewUnderlineAttribute(uiUnderlineDouble); + attr2 = uiNewUnderlineColorAttribute(uiUnderlineColorCustom, 1.0, 0.0, 0.5, 1.0); + appendWithAttribute("underline color", attr, attr2); + uiAttributedStringAppendUnattributed(attrstr, ". "); + + uiAttributedStringAppendUnattributed(attrstr, "Furthermore, there are attributes allowing for "); + attr = uiNewUnderlineAttribute(uiUnderlineSuggestion); + attr2 = uiNewUnderlineColorAttribute(uiUnderlineColorSpelling, 0, 0, 0, 0); + appendWithAttribute("special underlines for indicating spelling errors", attr, attr2); + uiAttributedStringAppendUnattributed(attrstr, " (and other types of errors) "); + + uiAttributedStringAppendUnattributed(attrstr, "and control over OpenType features such as ligatures (for instance, "); + otf = uiNewOpenTypeFeatures(); + uiOpenTypeFeaturesAdd(otf, 'l', 'i', 'g', 'a', 0); + attr = uiNewFeaturesAttribute(otf); + appendWithAttribute("afford", attr, NULL); + uiAttributedStringAppendUnattributed(attrstr, " vs. "); + uiOpenTypeFeaturesAdd(otf, 'l', 'i', 'g', 'a', 1); + attr = uiNewFeaturesAttribute(otf); + appendWithAttribute("afford", attr, NULL); + uiFreeOpenTypeFeatures(otf); + uiAttributedStringAppendUnattributed(attrstr, ").\n"); + + uiAttributedStringAppendUnattributed(attrstr, "Use the controls opposite to the text to control properties of the text."); +} + +static void handlerDraw(uiAreaHandler *a, uiArea *area, uiAreaDrawParams *p) +{ + uiDrawTextLayout *textLayout; + uiFontDescriptor defaultFont; + uiDrawTextLayoutParams params; + + params.String = attrstr; + uiFontButtonFont(fontButton, &defaultFont); + params.DefaultFont = &defaultFont; + params.Width = p->AreaWidth; + params.Align = (uiDrawTextAlign) uiComboboxSelected(alignment); + textLayout = uiDrawNewTextLayout(¶ms); + uiDrawText(p->Context, textLayout, 0, 0); + uiDrawFreeTextLayout(textLayout); + uiFreeFontButtonFont(&defaultFont); +} + +static void handlerMouseEvent(uiAreaHandler *a, uiArea *area, uiAreaMouseEvent *e) +{ + // do nothing +} + +static void handlerMouseCrossed(uiAreaHandler *ah, uiArea *a, int left) +{ + // do nothing +} + +static void handlerDragBroken(uiAreaHandler *ah, uiArea *a) +{ + // do nothing +} + +static int handlerKeyEvent(uiAreaHandler *ah, uiArea *a, uiAreaKeyEvent *e) +{ + // reject all keys + return 0; +} + +static void onFontChanged(uiFontButton *b, void *data) +{ + uiAreaQueueRedrawAll(area); +} + +static void onComboboxSelected(uiCombobox *b, void *data) +{ + uiAreaQueueRedrawAll(area); +} + +static int onClosing(uiWindow *w, void *data) +{ + uiControlDestroy(uiControl(mainwin)); + uiQuit(); + return 0; +} + +static int shouldQuit(void *data) +{ + uiControlDestroy(uiControl(mainwin)); + return 1; +} + +int main(void) +{ + uiInitOptions o; + const char *err; + uiBox *hbox, *vbox; + uiForm *form; + + handler.Draw = handlerDraw; + handler.MouseEvent = handlerMouseEvent; + handler.MouseCrossed = handlerMouseCrossed; + handler.DragBroken = handlerDragBroken; + handler.KeyEvent = handlerKeyEvent; + + memset(&o, 0, sizeof (uiInitOptions)); + err = uiInit(&o); + if (err != NULL) { + fprintf(stderr, "error initializing ui: %s\n", err); + uiFreeInitError(err); + return 1; + } + + uiOnShouldQuit(shouldQuit, NULL); + + makeAttributedString(); + + mainwin = uiNewWindow("libui Text-Drawing Example", 640, 480, 1); + uiWindowSetMargined(mainwin, 1); + uiWindowOnClosing(mainwin, onClosing, NULL); + + hbox = uiNewHorizontalBox(); + uiBoxSetPadded(hbox, 1); + uiWindowSetChild(mainwin, uiControl(hbox)); + + vbox = uiNewVerticalBox(); + uiBoxSetPadded(vbox, 1); + uiBoxAppend(hbox, uiControl(vbox), 0); + + fontButton = uiNewFontButton(); + uiFontButtonOnChanged(fontButton, onFontChanged, NULL); + uiBoxAppend(vbox, uiControl(fontButton), 0); + + form = uiNewForm(); + uiFormSetPadded(form, 1); + // TODO on OS X if this is set to 1 then the window can't resize; does the form not have the concept of stretchy trailing space? + uiBoxAppend(vbox, uiControl(form), 0); + + alignment = uiNewCombobox(); + // note that the items match with the values of the uiDrawTextAlign values + uiComboboxAppend(alignment, "Left"); + uiComboboxAppend(alignment, "Center"); + uiComboboxAppend(alignment, "Right"); + uiComboboxSetSelected(alignment, 0); // start with left alignment + uiComboboxOnSelected(alignment, onComboboxSelected, NULL); + uiFormAppend(form, "Alignment", uiControl(alignment), 0); + + area = uiNewArea(&handler); + uiBoxAppend(hbox, uiControl(area), 1); + + uiControlShow(uiControl(mainwin)); + uiMain(); + uiFreeAttributedString(attrstr); + uiUninit(); + return 0; +} diff --git a/dep/libui/examples/example.manifest b/dep/libui/examples/example.manifest new file mode 100644 index 0000000..41e7c9c --- /dev/null +++ b/dep/libui/examples/example.manifest @@ -0,0 +1,20 @@ + + + +Your application description here. + + + + + + + + + + + diff --git a/dep/libui/examples/example.static.manifest b/dep/libui/examples/example.static.manifest new file mode 100644 index 0000000..d8e83a8 --- /dev/null +++ b/dep/libui/examples/example.static.manifest @@ -0,0 +1,32 @@ + + + +Your application description here. + + + + + + + + + + + + + + + + diff --git a/dep/libui/examples/histogram/main.c b/dep/libui/examples/histogram/main.c new file mode 100644 index 0000000..f2b0e79 --- /dev/null +++ b/dep/libui/examples/histogram/main.c @@ -0,0 +1,309 @@ +// 13 october 2015 +#include +#include +#include +#include +#include "../../ui.h" + +uiWindow *mainwin; +uiArea *histogram; +uiAreaHandler handler; +uiSpinbox *datapoints[10]; +uiColorButton *colorButton; +int currentPoint = -1; + +// some metrics +#define xoffLeft 20 /* histogram margins */ +#define yoffTop 20 +#define xoffRight 20 +#define yoffBottom 20 +#define pointRadius 5 + +// helper to quickly set a brush color +static void setSolidBrush(uiDrawBrush *brush, uint32_t color, double alpha) +{ + uint8_t component; + + brush->Type = uiDrawBrushTypeSolid; + component = (uint8_t) ((color >> 16) & 0xFF); + brush->R = ((double) component) / 255; + component = (uint8_t) ((color >> 8) & 0xFF); + brush->G = ((double) component) / 255; + component = (uint8_t) (color & 0xFF); + brush->B = ((double) component) / 255; + brush->A = alpha; +} + +// and some colors +// names and values from https://msdn.microsoft.com/en-us/library/windows/desktop/dd370907%28v=vs.85%29.aspx +#define colorWhite 0xFFFFFF +#define colorBlack 0x000000 +#define colorDodgerBlue 0x1E90FF + +static void pointLocations(double width, double height, double *xs, double *ys) +{ + double xincr, yincr; + int i, n; + + xincr = width / 9; // 10 - 1 to make the last point be at the end + yincr = height / 100; + + for (i = 0; i < 10; i++) { + // get the value of the point + n = uiSpinboxValue(datapoints[i]); + // because y=0 is the top but n=0 is the bottom, we need to flip + n = 100 - n; + xs[i] = xincr * i; + ys[i] = yincr * n; + } +} + +static uiDrawPath *constructGraph(double width, double height, int extend) +{ + uiDrawPath *path; + double xs[10], ys[10]; + int i; + + pointLocations(width, height, xs, ys); + + path = uiDrawNewPath(uiDrawFillModeWinding); + + uiDrawPathNewFigure(path, xs[0], ys[0]); + for (i = 1; i < 10; i++) + uiDrawPathLineTo(path, xs[i], ys[i]); + + if (extend) { + uiDrawPathLineTo(path, width, height); + uiDrawPathLineTo(path, 0, height); + uiDrawPathCloseFigure(path); + } + + uiDrawPathEnd(path); + return path; +} + +static void graphSize(double clientWidth, double clientHeight, double *graphWidth, double *graphHeight) +{ + *graphWidth = clientWidth - xoffLeft - xoffRight; + *graphHeight = clientHeight - yoffTop - yoffBottom; +} + +static void handlerDraw(uiAreaHandler *a, uiArea *area, uiAreaDrawParams *p) +{ + uiDrawPath *path; + uiDrawBrush brush; + uiDrawStrokeParams sp; + uiDrawMatrix m; + double graphWidth, graphHeight; + double graphR, graphG, graphB, graphA; + + // fill the area with white + setSolidBrush(&brush, colorWhite, 1.0); + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathAddRectangle(path, 0, 0, p->AreaWidth, p->AreaHeight); + uiDrawPathEnd(path); + uiDrawFill(p->Context, path, &brush); + uiDrawFreePath(path); + + // figure out dimensions + graphSize(p->AreaWidth, p->AreaHeight, &graphWidth, &graphHeight); + + // clear sp to avoid passing garbage to uiDrawStroke() + // for example, we don't use dashing + memset(&sp, 0, sizeof (uiDrawStrokeParams)); + + // make a stroke for both the axes and the histogram line + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.Thickness = 2; + sp.MiterLimit = uiDrawDefaultMiterLimit; + + // draw the axes + setSolidBrush(&brush, colorBlack, 1.0); + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, + xoffLeft, yoffTop); + uiDrawPathLineTo(path, + xoffLeft, yoffTop + graphHeight); + uiDrawPathLineTo(path, + xoffLeft + graphWidth, yoffTop + graphHeight); + uiDrawPathEnd(path); + uiDrawStroke(p->Context, path, &brush, &sp); + uiDrawFreePath(path); + + // now transform the coordinate space so (0, 0) is the top-left corner of the graph + uiDrawMatrixSetIdentity(&m); + uiDrawMatrixTranslate(&m, xoffLeft, yoffTop); + uiDrawTransform(p->Context, &m); + + // now get the color for the graph itself and set up the brush + uiColorButtonColor(colorButton, &graphR, &graphG, &graphB, &graphA); + brush.Type = uiDrawBrushTypeSolid; + brush.R = graphR; + brush.G = graphG; + brush.B = graphB; + // we set brush->A below to different values for the fill and stroke + + // now create the fill for the graph below the graph line + path = constructGraph(graphWidth, graphHeight, 1); + brush.A = graphA / 2; + uiDrawFill(p->Context, path, &brush); + uiDrawFreePath(path); + + // now draw the histogram line + path = constructGraph(graphWidth, graphHeight, 0); + brush.A = graphA; + uiDrawStroke(p->Context, path, &brush, &sp); + uiDrawFreePath(path); + + // now draw the point being hovered over + if (currentPoint != -1) { + double xs[10], ys[10]; + + pointLocations(graphWidth, graphHeight, xs, ys); + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigureWithArc(path, + xs[currentPoint], ys[currentPoint], + pointRadius, + 0, 6.23, // TODO pi + 0); + uiDrawPathEnd(path); + // use the same brush as for the histogram lines + uiDrawFill(p->Context, path, &brush); + uiDrawFreePath(path); + } +} + +static int inPoint(double x, double y, double xtest, double ytest) +{ + // TODO switch to using a matrix + x -= xoffLeft; + y -= yoffTop; + return (x >= xtest - pointRadius) && + (x <= xtest + pointRadius) && + (y >= ytest - pointRadius) && + (y <= ytest + pointRadius); +} + +static void handlerMouseEvent(uiAreaHandler *a, uiArea *area, uiAreaMouseEvent *e) +{ + double graphWidth, graphHeight; + double xs[10], ys[10]; + int i; + + graphSize(e->AreaWidth, e->AreaHeight, &graphWidth, &graphHeight); + pointLocations(graphWidth, graphHeight, xs, ys); + + for (i = 0; i < 10; i++) + if (inPoint(e->X, e->Y, xs[i], ys[i])) + break; + if (i == 10) // not in a point + i = -1; + + currentPoint = i; + // TODO only redraw the relevant area + uiAreaQueueRedrawAll(histogram); +} + +static void handlerMouseCrossed(uiAreaHandler *ah, uiArea *a, int left) +{ + // do nothing +} + +static void handlerDragBroken(uiAreaHandler *ah, uiArea *a) +{ + // do nothing +} + +static int handlerKeyEvent(uiAreaHandler *ah, uiArea *a, uiAreaKeyEvent *e) +{ + // reject all keys + return 0; +} + +static void onDatapointChanged(uiSpinbox *s, void *data) +{ + uiAreaQueueRedrawAll(histogram); +} + +static void onColorChanged(uiColorButton *b, void *data) +{ + uiAreaQueueRedrawAll(histogram); +} + +static int onClosing(uiWindow *w, void *data) +{ + uiControlDestroy(uiControl(mainwin)); + uiQuit(); + return 0; +} + +static int shouldQuit(void *data) +{ + uiControlDestroy(uiControl(mainwin)); + return 1; +} + +int main(void) +{ + uiInitOptions o; + const char *err; + uiBox *hbox, *vbox; + int i; + uiDrawBrush brush; + + handler.Draw = handlerDraw; + handler.MouseEvent = handlerMouseEvent; + handler.MouseCrossed = handlerMouseCrossed; + handler.DragBroken = handlerDragBroken; + handler.KeyEvent = handlerKeyEvent; + + memset(&o, 0, sizeof (uiInitOptions)); + err = uiInit(&o); + if (err != NULL) { + fprintf(stderr, "error initializing ui: %s\n", err); + uiFreeInitError(err); + return 1; + } + + uiOnShouldQuit(shouldQuit, NULL); + + mainwin = uiNewWindow("libui Histogram Example", 640, 480, 1); + uiWindowSetMargined(mainwin, 1); + uiWindowOnClosing(mainwin, onClosing, NULL); + + hbox = uiNewHorizontalBox(); + uiBoxSetPadded(hbox, 1); + uiWindowSetChild(mainwin, uiControl(hbox)); + + vbox = uiNewVerticalBox(); + uiBoxSetPadded(vbox, 1); + uiBoxAppend(hbox, uiControl(vbox), 0); + + srand(time(NULL)); + for (i = 0; i < 10; i++) { + datapoints[i] = uiNewSpinbox(0, 100); + uiSpinboxSetValue(datapoints[i], rand() % 101); + uiSpinboxOnChanged(datapoints[i], onDatapointChanged, NULL); + uiBoxAppend(vbox, uiControl(datapoints[i]), 0); + } + + colorButton = uiNewColorButton(); + // TODO inline these + setSolidBrush(&brush, colorDodgerBlue, 1.0); + uiColorButtonSetColor(colorButton, + brush.R, + brush.G, + brush.B, + brush.A); + uiColorButtonOnChanged(colorButton, onColorChanged, NULL); + uiBoxAppend(vbox, uiControl(colorButton), 0); + + histogram = uiNewArea(&handler); + uiBoxAppend(hbox, uiControl(histogram), 1); + + uiControlShow(uiControl(mainwin)); + uiMain(); + uiUninit(); + return 0; +} diff --git a/dep/libui/examples/meson.build b/dep/libui/examples/meson.build new file mode 100644 index 0000000..3b9ab82 --- /dev/null +++ b/dep/libui/examples/meson.build @@ -0,0 +1,61 @@ +# 24 march 2019 + +libui_example_sources = [] +libui_example_link_args = [] +libui_example_cpp_extra_args = [] +if libui_OS == 'windows' + libui_example_manifest = 'example.manifest' + if libui_mode == 'static' + libui_example_manifest = 'example.static.manifest' + endif + libui_example_sources += [ + windows.compile_resources('resources.rc', + args: libui_manifest_args, + depend_files: [libui_example_manifest]), + ] + # because Microsoft's toolchain is dumb + if libui_MSVC + libui_example_link_args += ['/ENTRY:mainCRTStartup'] + endif +elif libui_OS == 'darwin' + # since we use a deployment target of 10.8, the non-C++11-compliant libstdc++ is chosen by default; we need C++11 + # see issue #302 for more details + libui_example_cpp_extra_args += ['--stdlib=libc++'] +endif + +libui_examples = { + 'controlgallery': { + 'sources': ['controlgallery/main.c'], + }, + 'histogram': { + 'sources': ['histogram/main.c'], + }, + 'cpp-multithread': { + 'sources': ['cpp-multithread/main.cpp'], + 'deps': [ + dependency('threads', + required: true), + ], + 'cpp_args': libui_example_cpp_extra_args, + 'link_args': libui_example_cpp_extra_args, + }, + 'drawtext': { + 'sources': ['drawtext/main.c'], + }, + 'timer': { + 'sources': ['timer/main.c'], + }, + 'datetime': { + 'sources': ['datetime/main.c'], + }, +} +foreach name, args : libui_examples + # TODO once we upgrade to 0.49.0, add pie: true + executable(name, args['sources'] + libui_example_sources, + dependencies: args.get('deps', []) + libui_binary_deps, + link_with: libui_libui, + cpp_args: args.get('cpp_args', []), + link_args: args.get('link_args', []) + libui_example_link_args, + gui_app: false, + install: false) +endforeach diff --git a/dep/libui/examples/resources.rc b/dep/libui/examples/resources.rc new file mode 100644 index 0000000..49f486c --- /dev/null +++ b/dep/libui/examples/resources.rc @@ -0,0 +1,13 @@ +// 30 may 2015 + +// this is a UTF-8 file +#pragma code_page(65001) + +// this is the Common Controls 6 manifest +// TODO set up the string values here +// 1 is the value of CREATEPROCESS_MANIFEST_RESOURCE_ID and 24 is the value of RT_MANIFEST; we use it directly to avoid needing to share winapi.h with the tests and examples +#ifndef _UI_STATIC +1 24 "example.manifest" +#else +1 24 "example.static.manifest" +#endif diff --git a/dep/libui/examples/timer/main.c b/dep/libui/examples/timer/main.c new file mode 100644 index 0000000..d1b80b9 --- /dev/null +++ b/dep/libui/examples/timer/main.c @@ -0,0 +1,64 @@ +#include +#include +#include +#include "../../ui.h" + +uiMultilineEntry *e; + +int sayTime(void *data) +{ + time_t t; + char *s; + + t = time(NULL); + s = ctime(&t); + + uiMultilineEntryAppend(e, s); + return 1; +} + +int onClosing(uiWindow *w, void *data) +{ + uiQuit(); + return 1; +} + +void saySomething(uiButton *b, void *data) +{ + uiMultilineEntryAppend(e, "Saying something\n"); +} + +int main(void) +{ + uiInitOptions o; + uiWindow *w; + uiBox *b; + uiButton *btn; + + memset(&o, 0, sizeof (uiInitOptions)); + if (uiInit(&o) != NULL) + abort(); + + w = uiNewWindow("Hello", 320, 240, 0); + uiWindowSetMargined(w, 1); + + b = uiNewVerticalBox(); + uiBoxSetPadded(b, 1); + uiWindowSetChild(w, uiControl(b)); + + e = uiNewMultilineEntry(); + uiMultilineEntrySetReadOnly(e, 1); + + btn = uiNewButton("Say Something"); + uiButtonOnClicked(btn, saySomething, NULL); + uiBoxAppend(b, uiControl(btn), 0); + + uiBoxAppend(b, uiControl(e), 1); + + uiTimer(1000, sayTime, NULL); + + uiWindowOnClosing(w, onClosing, NULL); + uiControlShow(uiControl(w)); + uiMain(); + return 0; +} diff --git a/dep/libui/meson.build b/dep/libui/meson.build new file mode 100644 index 0000000..9199a7e --- /dev/null +++ b/dep/libui/meson.build @@ -0,0 +1,176 @@ +# 17 march 2019 + +# TODO I'm not sure how to allow building 32-bit instead of 64-bit with meson + +# TODO remove cpp from this list once https://github.com/mesonbuild/meson/issues/5181 is settled; move it to the OS checks and under cpp-multithread +project('libui', ['c', 'cpp'], + meson_version: '>=0.48.0', + default_options: [ + 'buildtype=debug', # build debug by default + 'default_library=shared', # build shared libraries by default + 'layout=flat', # keep all outputs together by default + + # these are forced options, but meson doesn't let me set these up separately before I call project() (TODO https://github.com/mesonbuild/meson/issues/5179) + 'warning_level=3', # always max warnings + 'b_pch=false', # we don't want precompiled headers + 'b_staticpic=true', # use PIC even for static libraries + 'c_std=c99', # strict C99 + 'c_winlibs=', # we define our own Windows libraries + 'cpp_std=c++11', # strict C++11 + 'cpp_eh=sc', # shut the compiler up in some cases + 'cpp_winlibs=', # likewise as with c_winlibs + ], + license: 'MIT') + +# TODO after https://github.com/mesonbuild/meson/issues/5179 is settled, remove these +libui_OS = host_machine.system() +libui_MSVC = meson.get_compiler('c').get_id() == 'msvc' + +# TODO switch to tabs; the spaces are just so I can share this file while I'm writing it +libui_forced_options = { + 'warning_level': '3', # always max warnings + 'b_pch': 'false', # we don't want precompiled headers + 'b_staticpic': 'true', # use PIC even for static libraries + 'c_std': 'c99', # strict C99 + 'c_winlibs': '[]', # we define our own Windows libraries + 'cpp_std': 'c++11', # strict C++11 + 'cpp_eh': 'sc', # shut the compiler up in some cases + 'cpp_winlibs': '[]', # likewise as with c_winlibs +} +foreach name, value : libui_forced_options + # TODO rewrite this when https://github.com/mesonbuild/meson/issues/5181 is settled + if not ((name == 'c_winlibs' or name == 'cpp_eh' or name == 'cpp_winlibs') and not libui_MSVC) and not (name == 'c_std' and libui_MSVC) + actual = '@0@'.format(get_option(name)) + if actual != value + error('sorry, but libui requires that option ' + name + ' has the default value ' + value) + endif + endif +endforeach + +libui_OS = host_machine.system() +libui_MSVC = meson.get_compiler('c').get_id() == 'msvc' + +if libui_OS == 'darwin' + add_languages('objc', + required: true) +endif + +libui_mode = get_option('default_library') +if libui_mode == 'both' + error('sorry, but libui does not support building both shared and static libraries at the same time, because Windows resource file rules differ between the two') +endif + +libui_is_debug = get_option('buildtype').startswith('debug') + +libui_project_compile_args = [] +libui_project_link_args = [] + +if libui_OS == 'darwin' + libui_macosx_version_min = '-mmacosx-version-min=10.8' + libui_project_compile_args += [libui_macosx_version_min] + libui_project_link_args += [libui_macosx_version_min] +endif + +if libui_MSVC + # TODO subsystem version + + libui_project_compile_args += [ + '/wd4100', + '/bigobj', + ] + if libui_is_debug + libui_project_compile_args += ['/RTC1', '/RTCs', '/RTCu'] + endif + + libui_project_link_args += [ + '/LARGEADDRESSAWARE', + '/INCREMENTAL:NO', + '/MANIFEST:NO', + ] + + # TODO autogenerate a .def file? +else + libui_project_compile_args += [ + '-Wno-unused-parameter', + '-Wno-switch', + ] + + if libui_OS == 'windows' + # don't require shipping the MinGW-w64 DLLs + libui_project_link_args += [ + '-static', + '-static-libgcc', + '-static-libstdc++', + ] + endif +endif + +# TODO come up with a better way to do this, both for libui (the compiler define, used by winapi.hpp, and the manifest args) and for the binaries (the manifest args) +# TODO (after the above TODO is resolved) move that below the part below that actually adds these arguments +libui_manifest_args = [] +if libui_mode == 'static' + libui_project_compile_args += ['-D_UI_STATIC'] + libui_manifest_args = ['-D_UI_STATIC'] +endif + +add_project_arguments(libui_project_compile_args, + language: ['c', 'cpp', 'objc']) +add_project_link_arguments(libui_project_link_args, + language: ['c', 'cpp', 'objc']) + +# TODO: +# meson determins whether -Wl,--no-undefined is provided via +# built-in option b_lundef, and it's true by default, which is what +# we want (so I don't make mistakes like asking for unknown +# functions in my dependencies). However, meson also is smart +# about specifying this properly on systems that don't support it, like +# FreeBSD (where I had the comment "figure out why FreeBSD +# follows linked libraries here" when I was on cmake) and OpenBSD +# (according to someone on freenode #mesonbuild), but it isn't clear +# whether it's just ignored or if the value is forced to false. +# Therefore, once this is determined, we can uncomment the +# following. +libui_libui_link_args = [] +#if not libui_MSVC and get_option("b_lundef") + # TODO what should this be on MSVC? +# libui_libui_link_args += ['-Wl,--no-allow-shlib-undefined'] +#endif + +libui_sources = [] +libui_deps = [] +libui_soversion = '' +libui_rpath = '' +subdir('common') +if libui_OS == 'windows' + subdir('windows') + install_headers('ui_windows.h') +elif libui_OS == 'darwin' + subdir('darwin') + install_headers('ui_darwin.h') +else + subdir('unix') + install_headers('ui_unix.h') +endif +libui_libui = library('ui', libui_sources, + dependencies: libui_deps, + build_rpath: libui_rpath, + install_rpath: libui_rpath, + name_prefix: 'lib', # always call it libui, even in Windows DLLs + install: true, + gnu_symbol_visibility: 'hidden', + c_args: ['-Dlibui_EXPORTS'], + cpp_args: ['-Dlibui_EXPORTS'], + objc_args: ['-Dlibui_EXPORTS'], + link_args: libui_libui_link_args, + soversion: libui_soversion, + darwin_versions: []) # TODO +install_headers('ui.h') + +# TODO when the API is stable enough to be versioned, create a pkg-config file (https://mesonbuild.com/Pkgconfig-module.html) and a declare_dependency() section too + +libui_binary_deps = [] +if libui_mode == 'static' + libui_binary_deps = libui_deps +endif +subdir('test') +subdir('examples') diff --git a/dep/libui/stats.osxdrawtext b/dep/libui/stats.osxdrawtext new file mode 100644 index 0000000..15c9c6c --- /dev/null +++ b/dep/libui/stats.osxdrawtext @@ -0,0 +1,43 @@ +diff --git a/darwin/drawtext.m b/darwin/drawtext.m +index a84b68b..c95bbde 100644 +--- a/darwin/drawtext.m ++++ b/darwin/drawtext.m +@@ -108,7 +108,7 @@ static CFAttributedStringRef attrstrToCoreFoundation(uiAttributedString *s, uiDr + boundsNoLeading = CTLineGetBoundsWithOptions(line, kCTLineBoundsExcludeTypographicLeading); + + // this is equivalent to boundsNoLeading.size.height + boundsNoLeading.origin.y (manually verified) +- ascent = bounds.size.height + bounds.origin.y; ++if(i!=5) ascent = bounds.size.height + bounds.origin.y; + descent = -boundsNoLeading.origin.y; + // TODO does this preserve leading sign? + leading = -bounds.origin.y - descent; +@@ -119,11 +119,20 @@ static CFAttributedStringRef attrstrToCoreFoundation(uiAttributedString *s, uiDr + if (leading > 0) + leading = floor(leading + 0.5); + ++NSLog(@"line %d", (int)i); ++NSLog(@"ypos %g", ypos); ++if (i>0) { ++NSLog(@"expected Y: %g", metrics[i - 1].Y - metrics[i - 1].Height); ++} ++ + metrics[i].X = origins[i].x; + metrics[i].Y = origins[i].y - descent - leading; + metrics[i].Width = bounds.size.width; + metrics[i].Height = ascent + descent + leading; + ++NSLog(@"o %g a %g d %g l %g", origins[i].y, ascent, descent, leading); ++NSLog(@"actual Y: %g height: %g", metrics[i].Y, metrics[i].Height); ++ + metrics[i].BaselineY = origins[i].y; + metrics[i].Ascent = ascent; + metrics[i].Descent = descent; +@@ -148,7 +157,7 @@ static CFAttributedStringRef attrstrToCoreFoundation(uiAttributedString *s, uiDr + metrics[i].BaselineY = size.height - metrics[i].BaselineY; + // TODO also adjust by metrics[i].Height? + } +- ++NSLog(@"==="); + uiFree(origins); + return metrics; + } diff --git a/dep/libui/test/OLD_page16.c b/dep/libui/test/OLD_page16.c new file mode 100644 index 0000000..80ac013 --- /dev/null +++ b/dep/libui/test/OLD_page16.c @@ -0,0 +1,143 @@ +// 21 june 2016 +#include "test.h" + +static uiTableModelHandler mh; + +static int modelNumColumns(uiTableModelHandler *mh, uiTableModel *m) +{ + return 9; +} + +static uiTableModelColumnType modelColumnType(uiTableModelHandler *mh, uiTableModel *m, int column) +{ + if (column == 3 || column == 4) + return uiTableModelColumnColor; + if (column == 5) + return uiTableModelColumnImage; + if (column == 7 || column == 8) + return uiTableModelColumnInt; + return uiTableModelColumnString; +} + +static int modelNumRows(uiTableModelHandler *mh, uiTableModel *m) +{ + return 15; +} + +static uiImage *img[2]; +static char row9text[1024]; +static int yellowRow = -1; +static int checkStates[15]; + +static void *modelCellValue(uiTableModelHandler *mh, uiTableModel *m, int row, int col) +{ + char buf[256]; + + if (col == 3) { + if (row == yellowRow) + return uiTableModelGiveColor(1, 1, 0, 1); + if (row == 3) + return uiTableModelGiveColor(1, 0, 0, 1); + if (row == 11) + return uiTableModelGiveColor(0, 0.5, 1, 0.5); + return NULL; + } + if (col == 4) { + if ((row % 2) == 1) + return uiTableModelGiveColor(0.5, 0, 0.75, 1); + return NULL; + } + if (col == 5) { + if (row < 8) + return img[0]; + return img[1]; + } + if (col == 7) + return uiTableModelGiveInt(checkStates[row]); + if (col == 8) { + if (row == 0) + return uiTableModelGiveInt(0); + if (row == 13) + return uiTableModelGiveInt(100); + if (row == 14) + return uiTableModelGiveInt(-1); + return uiTableModelGiveInt(50); + } + switch (col) { + case 0: + sprintf(buf, "Row %d", row); + break; + case 2: + if (row == 9) + return uiTableModelStrdup(row9text); + // fall through + case 1: + strcpy(buf, "Part"); + break; + case 6: + strcpy(buf, "Make Yellow"); + break; + } + return uiTableModelStrdup(buf); +} + +static void modelSetCellValue(uiTableModelHandler *mh, uiTableModel *m, int row, int col, const void *val) +{ + if (row == 9 && col == 2) + strcpy(row9text, (const char *) val); + if (col == 6) + yellowRow = row; + if (col == 7) + checkStates[row] = uiTableModelTakeInt(val); +} + +uiBox *makePage16(void) +{ + uiBox *page16; + uiTableModel *m; + uiTable *t; + uiTableColumn *tc; + + img[0] = uiNewImage(16, 16); + appendImageNamed(img[0], "andlabs_16x16test_24june2016.png"); + appendImageNamed(img[0], "andlabs_32x32test_24june2016.png"); + img[1] = uiNewImage(16, 16); + appendImageNamed(img[1], "tango-icon-theme-0.8.90_16x16_x-office-spreadsheet.png"); + appendImageNamed(img[1], "tango-icon-theme-0.8.90_32x32_x-office-spreadsheet.png"); + + strcpy(row9text, "Part"); + + memset(checkStates, 0, 15 * sizeof (int)); + + page16 = newVerticalBox(); + + mh.NumColumns = modelNumColumns; + mh.ColumnType = modelColumnType; + mh.NumRows = modelNumRows; + mh.CellValue = modelCellValue; + mh.SetCellValue = modelSetCellValue; + m = uiNewTableModel(&mh); + + t = uiNewTable(m); + uiBoxAppend(page16, uiControl(t), 1); + + uiTableAppendTextColumn(t, "Column 1", 0); + + tc = uiTableAppendColumn(t, "Column 2"); + uiTableColumnAppendImagePart(tc, 5, 0); + uiTableColumnAppendTextPart(tc, 1, 0); + uiTableColumnAppendTextPart(tc, 2, 1); + uiTableColumnPartSetTextColor(tc, 1, 4); + uiTableColumnPartSetEditable(tc, 2, 1); + + uiTableSetRowBackgroundColorModelColumn(t, 3); + + tc = uiTableAppendColumn(t, "Buttons"); + uiTableColumnAppendCheckboxPart(tc, 7, 0); + uiTableColumnAppendButtonPart(tc, 6, 1); + + tc = uiTableAppendColumn(t, "Progress Bar"); + uiTableColumnAppendProgressBarPart(tc, 8, 0); + + return page16; +} diff --git a/dep/libui/test/drawtests.c b/dep/libui/test/drawtests.c new file mode 100644 index 0000000..5c40929 --- /dev/null +++ b/dep/libui/test/drawtests.c @@ -0,0 +1,1979 @@ +// 9 october 2015 +#include "test.h" + +// TODO +// - test multiple clips +// - test saving and restoring clips +// - copy tests from https://github.com/Microsoft/WinObjC + +struct drawtest { + const char *name; + void (*draw)(uiAreaDrawParams *p); + // TODO mouse event +}; + +static void drawOriginal(uiAreaDrawParams *p) +{ + uiDrawPath *path; + uiDrawBrush brush; + uiDrawStrokeParams sp; + + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + brush.Type = uiDrawBrushTypeSolid; + brush.A = 1; + + brush.R = 1; + brush.G = 0; + brush.B = 0; + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, p->ClipX + 5, p->ClipY + 5); + uiDrawPathLineTo(path, (p->ClipX + p->ClipWidth) - 5, (p->ClipY + p->ClipHeight) - 5); + uiDrawPathEnd(path); + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.Thickness = 1; + sp.MiterLimit = uiDrawDefaultMiterLimit; + uiDrawStroke(p->Context, path, &brush, &sp); + uiDrawFreePath(path); + + brush.R = 0; + brush.G = 0; + brush.B = 0.75; + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, p->ClipX, p->ClipY); + uiDrawPathLineTo(path, p->ClipX + p->ClipWidth, p->ClipY); + uiDrawPathLineTo(path, 50, 150); + uiDrawPathLineTo(path, 50, 50); + uiDrawPathCloseFigure(path); + uiDrawPathEnd(path); + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinRound; + sp.Thickness = 5; + uiDrawStroke(p->Context, path, &brush, &sp); + uiDrawFreePath(path); + + brush.R = 0; + brush.G = 0.75; + brush.B = 0; + brush.A = 0.5; + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathAddRectangle(path, 120, 80, 50, 50); + uiDrawPathEnd(path); + uiDrawFill(p->Context, path, &brush); + uiDrawFreePath(path); + brush.A = 1; + + brush.R = 0; + brush.G = 0.5; + brush.B = 0; + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, 5.5, 10.5); + uiDrawPathLineTo(path, 5.5, 50.5); + uiDrawPathEnd(path); + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.Thickness = 1; + sp.MiterLimit = uiDrawDefaultMiterLimit; + uiDrawStroke(p->Context, path, &brush, &sp); + uiDrawFreePath(path); + + brush.R = 0.5; + brush.G = 0.75; + brush.B = 0; + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, 400, 100); + uiDrawPathArcTo(path, + 400, 100, + 50, + 30. * (uiPi / 180.), + 300. * (uiPi / 180.), + 0); + // the sweep test below doubles as a clockwise test so a checkbox isn't needed anymore + uiDrawPathLineTo(path, 400, 100); + uiDrawPathNewFigureWithArc(path, + 510, 100, + 50, + 30. * (uiPi / 180.), + 300. * (uiPi / 180.), + 0); + uiDrawPathCloseFigure(path); + // and now with 330 to make sure sweeps work properly + uiDrawPathNewFigure(path, 400, 210); + uiDrawPathArcTo(path, + 400, 210, + 50, + 30. * (uiPi / 180.), + 330. * (uiPi / 180.), + 0); + uiDrawPathLineTo(path, 400, 210); + uiDrawPathNewFigureWithArc(path, + 510, 210, + 50, + 30. * (uiPi / 180.), + 330. * (uiPi / 180.), + 0); + uiDrawPathCloseFigure(path); + uiDrawPathEnd(path); + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.Thickness = 1; + sp.MiterLimit = uiDrawDefaultMiterLimit; + uiDrawStroke(p->Context, path, &brush, &sp); + uiDrawFreePath(path); + + brush.R = 0; + brush.G = 0.5; + brush.B = 0.75; + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, 300, 300); + uiDrawPathBezierTo(path, + 350, 320, + 310, 390, + 435, 372); + uiDrawPathEnd(path); + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.Thickness = 1; + sp.MiterLimit = uiDrawDefaultMiterLimit; + uiDrawStroke(p->Context, path, &brush, &sp); + uiDrawFreePath(path); +} + +static void drawArcs(uiAreaDrawParams *p) +{ + uiDrawPath *path; + int start = 20; + int step = 20; + int rad = 25; + int x, y; + double angle; + double add; + int i; + uiDrawBrush brush; + uiDrawStrokeParams sp; + + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + path = uiDrawNewPath(uiDrawFillModeWinding); + + add = (2.0 * uiPi) / 12; + + x = start + rad; + y = start + rad; + angle = 0; + for (i = 0; i < 13; i++) { + uiDrawPathNewFigureWithArc(path, + x, y, + rad, + 0, angle, + 0); + angle += add; + x += 2 * rad + step; + } + + y += 2 * rad + step; + x = start + rad; + angle = 0; + for (i = 0; i < 13; i++) { + uiDrawPathNewFigure(path, x, y); + uiDrawPathArcTo(path, + x, y, + rad, + 0, angle, + 0); + angle += add; + x += 2 * rad + step; + } + + y += 2 * rad + step; + x = start + rad; + angle = 0; + for (i = 0; i < 13; i++) { + uiDrawPathNewFigureWithArc(path, + x, y, + rad, + (uiPi / 4), angle, + 0); + angle += add; + x += 2 * rad + step; + } + + y += 2 * rad + step; + x = start + rad; + angle = 0; + for (i = 0; i < 13; i++) { + uiDrawPathNewFigure(path, x, y); + uiDrawPathArcTo(path, + x, y, + rad, + (uiPi / 4), angle, + 0); + angle += add; + x += 2 * rad + step; + } + + y += 2 * rad + step; + x = start + rad; + angle = 0; + for (i = 0; i < 13; i++) { + uiDrawPathNewFigureWithArc(path, + x, y, + rad, + uiPi + (uiPi / 5), angle, + 0); + angle += add; + x += 2 * rad + step; + } + + y += 2 * rad + step; + x = start + rad; + angle = 0; + for (i = 0; i < 13; i++) { + uiDrawPathNewFigure(path, x, y); + uiDrawPathArcTo(path, + x, y, + rad, + uiPi + (uiPi / 5), angle, + 0); + angle += add; + x += 2 * rad + step; + } + + uiDrawPathEnd(path); + + brush.Type = uiDrawBrushTypeSolid; + brush.R = 0; + brush.G = 0; + brush.B = 0; + brush.A = 1; + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.Thickness = 1; + sp.MiterLimit = uiDrawDefaultMiterLimit; + uiDrawStroke(p->Context, path, &brush, &sp); + + uiDrawFreePath(path); +} + +// Direct2D Documentation Code + +static void d2dColorToRGB(uint32_t color, double *r, double *g, double *b) +{ + uint8_t rr, gg, bb; + + rr = (color & 0xFF0000) >> 16; + gg = (color & 0x00FF00) >> 8; + bb = color & 0x0000FF; + *r = ((double) rr) / 255.0; + *g = ((double) gg) / 255.0; + *b = ((double) bb) / 255.0; +} +#define d2dBlack 0x000000 +#define d2dLightSlateGray 0x778899 +#define d2dCornflowerBlue 0x6495ED +#define d2dWhite 0xFFFFFF +#define d2dYellowGreen 0x9ACD32 +#define d2dYellow 0xFFFF00 +#define d2dForestGreen 0x228B22 +#define d2dOliveDrab 0x6B8E23 +#define d2dLightSkyBlue 0x87CEFA + +static void d2dSolidBrush(uiDrawBrush *brush, uint32_t color, double alpha) +{ + brush->Type = uiDrawBrushTypeSolid; + d2dColorToRGB(color, &(brush->R), &(brush->G), &(brush->B)); + brush->A = alpha; +} + +static void d2dClear(uiAreaDrawParams *p, uint32_t color, double alpha) +{ + uiDrawPath *path; + uiDrawBrush brush; + + d2dSolidBrush(&brush, color, alpha); + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathAddRectangle(path, 0, 0, p->AreaWidth, p->AreaHeight); + uiDrawPathEnd(path); + uiDrawFill(p->Context, path, &brush); + uiDrawFreePath(path); +} + +// from https://msdn.microsoft.com/en-us/library/windows/desktop/hh780340%28v=vs.85%29.aspx +// also at https://msdn.microsoft.com/en-us/library/windows/desktop/dd535473%28v=vs.85%29.aspx +static void drawD2DW8QS(uiAreaDrawParams *p) +{ + uiDrawPath *path; + uiDrawBrush brush; + + d2dSolidBrush(&brush, d2dBlack, 1.0); + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathAddRectangle(path, + 100, + 100, + (p->AreaWidth - 100) - 100, + (p->AreaHeight - 100) - 100); + uiDrawPathEnd(path); + uiDrawFill(p->Context, path, &brush); + uiDrawFreePath(path); +} + +// from https://msdn.microsoft.com/en-us/library/windows/desktop/dd370994%28v=vs.85%29.aspx +static void drawD2DSimpleApp(uiAreaDrawParams *p) +{ + uiDrawPath *path; + uiDrawBrush lightSlateGray; + uiDrawBrush cornflowerBlue; + uiDrawStrokeParams sp; + int x, y; + + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + d2dSolidBrush(&lightSlateGray, d2dLightSlateGray, 1.0); + d2dSolidBrush(&cornflowerBlue, d2dCornflowerBlue, 1.0); + + d2dClear(p, d2dWhite, 1.0); + + sp.Thickness = 0.5; + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + + for (x = 0; x < p->AreaWidth; x += 10) { + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, x, 0); + uiDrawPathLineTo(path, x, p->AreaHeight); + uiDrawPathEnd(path); + uiDrawStroke(p->Context, path, &lightSlateGray, &sp); + uiDrawFreePath(path); + } + + for (y = 0; y < p->AreaHeight; y += 10) { + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, 0, y); + uiDrawPathLineTo(path, p->AreaWidth, y); + uiDrawPathEnd(path); + uiDrawStroke(p->Context, path, &lightSlateGray, &sp); + uiDrawFreePath(path); + } + + double left, top, right, bottom; + + left = p->AreaWidth / 2.0 - 50.0; + right = p->AreaWidth / 2.0 + 50.0; + top = p->AreaHeight / 2.0 - 50.0; + bottom = p->AreaHeight / 2.0 + 50.0; + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathAddRectangle(path, left, top, right - left, bottom - top); + uiDrawPathEnd(path); + uiDrawFill(p->Context, path, &lightSlateGray); + uiDrawFreePath(path); + + left = p->AreaWidth / 2.0 - 100.0; + right = p->AreaWidth / 2.0 + 100.0; + top = p->AreaHeight / 2.0 - 100.0; + bottom = p->AreaHeight / 2.0 + 100.0; + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathAddRectangle(path, left, top, right - left, bottom - top); + uiDrawPathEnd(path); + sp.Thickness = 1.0; + uiDrawStroke(p->Context, path, &cornflowerBlue, &sp); + uiDrawFreePath(path); +} + +// TODO? https://msdn.microsoft.com/en-us/library/windows/desktop/dd372260(v=vs.85).aspx + +// TODO https://msdn.microsoft.com/en-us/library/windows/desktop/dd756654%28v=vs.85%29.aspx + +// TODO? all subsections too? https://msdn.microsoft.com/en-us/library/windows/desktop/hh973240%28v=vs.85%29.aspx + +// TODO differing examples of? https://msdn.microsoft.com/en-us/library/windows/desktop/dd756651%28v=vs.85%29.aspx + +// from https://msdn.microsoft.com/en-us/library/windows/desktop/dd756680%28v=vs.85%29.aspx +static void drawD2DSolidBrush(uiAreaDrawParams *p) +{ + uiDrawPath *path; + uiDrawBrush black; + uiDrawBrush yellowGreen; + uiDrawStrokeParams sp; + + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + d2dSolidBrush(&black, d2dBlack, 1.0); + d2dSolidBrush(&yellowGreen, d2dYellowGreen, 1.0); + + path = uiDrawNewPath(uiDrawFillModeWinding); + // the example doesn't define a rectangle + // 150x150 seems to be right given the other examples though + uiDrawPathAddRectangle(path, 25, 25, 150, 150); + uiDrawPathEnd(path); + + uiDrawFill(p->Context, path, &yellowGreen); + sp.Thickness = 1.0; + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + uiDrawStroke(p->Context, path, &black, &sp); + + uiDrawFreePath(path); +} + +// from https://msdn.microsoft.com/en-us/library/windows/desktop/dd756678%28v=vs.85%29.aspx +static void drawD2DLinearBrush(uiAreaDrawParams *p) +{ + uiDrawPath *path; + uiDrawBrush black; + uiDrawBrush gradient; + uiDrawBrushGradientStop stops[2]; + uiDrawStrokeParams sp; + + uiDrawMatrix m; + + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + // leave some room + uiDrawMatrixSetIdentity(&m); + uiDrawMatrixTranslate(&m, 25, 25); + uiDrawTransform(p->Context, &m); + + gradient.Type = uiDrawBrushTypeLinearGradient; + gradient.X0 = 0; + gradient.Y0 = 0; + gradient.X1 = 150; + gradient.Y1 = 150; + stops[0].Pos = 0.0; + d2dColorToRGB(d2dYellow, &(stops[0].R), &(stops[0].G), &(stops[0].B)); + stops[0].A = 1.0; + stops[1].Pos = 1.0; + d2dColorToRGB(d2dForestGreen, &(stops[1].R), &(stops[1].G), &(stops[1].B)); + stops[1].A = 1.0; + gradient.Stops = stops; + gradient.NumStops = 2; + + d2dSolidBrush(&black, d2dBlack, 1.0); + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathAddRectangle(path, 0, 0, 150, 150); + uiDrawPathEnd(path); + + uiDrawFill(p->Context, path, &gradient); + sp.Thickness = 1.0; + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + uiDrawStroke(p->Context, path, &black, &sp); + + uiDrawFreePath(path); +} + +// from https://msdn.microsoft.com/en-us/library/windows/desktop/dd756679%28v=vs.85%29.aspx +// TODO expand this to change the origin point with a mouse click (not in the original but useful to have) +static void drawD2DRadialBrush(uiAreaDrawParams *p) +{ + uiDrawPath *path; + uiDrawBrush black; + uiDrawBrush gradient; + uiDrawBrushGradientStop stops[2]; + uiDrawStrokeParams sp; + + uiDrawMatrix m; + + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + // leave some room + uiDrawMatrixSetIdentity(&m); + uiDrawMatrixTranslate(&m, 25, 25); + uiDrawTransform(p->Context, &m); + + gradient.Type = uiDrawBrushTypeRadialGradient; + gradient.X0 = 75; + gradient.Y0 = 75; + gradient.X1 = 75; + gradient.Y1 = 75; + gradient.OuterRadius = 75; + stops[0].Pos = 0.0; + d2dColorToRGB(d2dYellow, &(stops[0].R), &(stops[0].G), &(stops[0].B)); + stops[0].A = 1.0; + stops[1].Pos = 1.0; + d2dColorToRGB(d2dForestGreen, &(stops[1].R), &(stops[1].G), &(stops[1].B)); + stops[1].A = 1.0; + gradient.Stops = stops; + gradient.NumStops = 2; + + d2dSolidBrush(&black, d2dBlack, 1.0); + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, 150, 75); + uiDrawPathArcTo(path, + 75, 75, + 75, + 0, + 2 * uiPi, + 0); + uiDrawPathEnd(path); + + uiDrawFill(p->Context, path, &gradient); + sp.Thickness = 1.0; + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + uiDrawStroke(p->Context, path, &black, &sp); + + uiDrawFreePath(path); +} + +// TODO https://msdn.microsoft.com/en-us/library/windows/desktop/dd756677%28v=vs.85%29.aspx + +// TODO? other pages have some of these https://msdn.microsoft.com/en-us/library/windows/desktop/dd756653%28v=vs.85%29.aspx + +// from https://msdn.microsoft.com/en-us/library/windows/desktop/ee264309%28v=vs.85%29.aspx +static void drawD2DPathGeometries(uiAreaDrawParams *p) +{ + uiDrawPath *leftMountain; + uiDrawPath *rightMountain; + uiDrawPath *sun; + uiDrawPath *sunRays; + uiDrawPath *river; + uiDrawBrush radial; + uiDrawBrush scene; + uiDrawStrokeParams sp; + uiDrawBrushGradientStop stops[2]; + + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + // TODO this is definitely wrong but the example doesn't have the right brush in it + radial.Type = uiDrawBrushTypeRadialGradient; + radial.X0 = 75; + radial.Y0 = 75; + radial.X1 = 75; + radial.Y1 = 75; + radial.OuterRadius = 75; + stops[0].Pos = 0.0; + d2dColorToRGB(d2dYellow, &(stops[0].R), &(stops[0].G), &(stops[0].B)); + stops[0].A = 1.0; + stops[1].Pos = 1.0; + d2dColorToRGB(d2dForestGreen, &(stops[1].R), &(stops[1].G), &(stops[1].B)); + stops[1].A = 1.0; + radial.Stops = stops; + radial.NumStops = 2; + + leftMountain = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(leftMountain, 346, 255); + uiDrawPathLineTo(leftMountain, 267, 177); + uiDrawPathLineTo(leftMountain, 236, 192); + uiDrawPathLineTo(leftMountain, 212, 160); + uiDrawPathLineTo(leftMountain, 156, 255); + uiDrawPathLineTo(leftMountain, 346, 255); + uiDrawPathCloseFigure(leftMountain); + uiDrawPathEnd(leftMountain); + + rightMountain = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(rightMountain, 575, 263); + uiDrawPathLineTo(rightMountain, 481, 146); + uiDrawPathLineTo(rightMountain, 449, 181); + uiDrawPathLineTo(rightMountain, 433, 159); + uiDrawPathLineTo(rightMountain, 401, 214); + uiDrawPathLineTo(rightMountain, 381, 199); + uiDrawPathLineTo(rightMountain, 323, 263); + uiDrawPathLineTo(rightMountain, 575, 263); + uiDrawPathCloseFigure(rightMountain); + uiDrawPathEnd(rightMountain); + + sun = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigureWithArc(sun, + (440.0 - 270.0) / 2 + 270.0, 255, + 85, + uiPi, uiPi, + 0); + uiDrawPathCloseFigure(sun); + uiDrawPathEnd(sun); + + // the original examples had these as hollow figures + // we don't support them, so we'll have to stroke it separately + sunRays = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(sunRays, 299, 182); + uiDrawPathBezierTo(sunRays, + 299, 182, + 294, 176, + 285, 178); + uiDrawPathBezierTo(sunRays, + 276, 179, + 272, 173, + 272, 173); + uiDrawPathNewFigure(sunRays, 354, 156); + uiDrawPathBezierTo(sunRays, + 354, 156, + 358, 149, + 354, 142); + uiDrawPathBezierTo(sunRays, + 349, 134, + 354, 127, + 354, 127); + uiDrawPathNewFigure(sunRays, 322, 164); + uiDrawPathBezierTo(sunRays, + 322, 164, + 322, 156, + 314, 152); + uiDrawPathBezierTo(sunRays, + 306, 149, + 305, 141, + 305, 141); + uiDrawPathNewFigure(sunRays, 385, 164); + uiDrawPathBezierTo(sunRays, + 385, 164, + 392, 161, + 394, 152); + uiDrawPathBezierTo(sunRays, + 395, 144, + 402, 141, + 402, 142); + uiDrawPathNewFigure(sunRays, 408, 182); + uiDrawPathBezierTo(sunRays, + 408, 182, + 416, 184, + 422, 178); + uiDrawPathBezierTo(sunRays, + 428, 171, + 435, 173, + 435, 173); + uiDrawPathEnd(sunRays); + + river = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(river, 183, 392); + uiDrawPathBezierTo(river, + 238, 284, + 472, 345, + 356, 303); + uiDrawPathBezierTo(river, + 237, 261, + 333, 256, + 333, 256); + uiDrawPathBezierTo(river, + 335, 257, + 241, 261, + 411, 306); + uiDrawPathBezierTo(river, + 574, 350, + 288, 324, + 296, 392); + uiDrawPathEnd(river); + + d2dClear(p, d2dWhite, 1.0); + + // TODO draw the grid + + uiDrawFill(p->Context, sun, &radial); + + d2dSolidBrush(&scene, d2dBlack, 1.0); + sp.Thickness = 1.0; + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + uiDrawStroke(p->Context, sun, &scene, &sp); + uiDrawStroke(p->Context, sunRays, &scene, &sp); + + d2dSolidBrush(&scene, d2dOliveDrab, 1.0); + uiDrawFill(p->Context, leftMountain, &scene); + + d2dSolidBrush(&scene, d2dBlack, 1.0); + uiDrawStroke(p->Context, leftMountain, &scene, &sp); + + d2dSolidBrush(&scene, d2dLightSkyBlue, 1.0); + uiDrawFill(p->Context, river, &scene); + + d2dSolidBrush(&scene, d2dBlack, 1.0); + uiDrawStroke(p->Context, river, &scene, &sp); + + d2dSolidBrush(&scene, d2dYellowGreen, 1.0); + uiDrawFill(p->Context, rightMountain, &scene); + + d2dSolidBrush(&scene, d2dBlack, 1.0); + uiDrawStroke(p->Context, rightMountain, &scene, &sp); + + uiDrawFreePath(leftMountain); + uiDrawFreePath(rightMountain); + uiDrawFreePath(sun); + uiDrawFreePath(sunRays); + uiDrawFreePath(river); +} + +// TODO https://msdn.microsoft.com/en-us/library/windows/desktop/dd756690%28v=vs.85%29.aspx + +// from https://msdn.microsoft.com/en-us/library/windows/desktop/dd756681%28v=vs.85%29.aspx +static void drawD2DGeometryGroup(uiAreaDrawParams *p) +{ + uiDrawPath *alternate; + uiDrawPath *winding; + uiDrawBrush fill; + uiDrawBrush stroke; + uiDrawStrokeParams sp; + uiDrawMatrix m; + + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + alternate = uiDrawNewPath(uiDrawFillModeAlternate); + uiDrawPathNewFigureWithArc(alternate, + 105, 105, + 25, + 0, 2 * uiPi, + 0); + uiDrawPathNewFigureWithArc(alternate, + 105, 105, + 50, + 0, 2 * uiPi, + 0); + uiDrawPathNewFigureWithArc(alternate, + 105, 105, + 75, + 0, 2 * uiPi, + 0); + uiDrawPathNewFigureWithArc(alternate, + 105, 105, + 100, + 0, 2 * uiPi, + 0); + uiDrawPathEnd(alternate); + + winding = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigureWithArc(winding, + 105, 105, + 25, + 0, 2 * uiPi, + 0); + uiDrawPathNewFigureWithArc(winding, + 105, 105, + 50, + 0, 2 * uiPi, + 0); + uiDrawPathNewFigureWithArc(winding, + 105, 105, + 75, + 0, 2 * uiPi, + 0); + uiDrawPathNewFigureWithArc(winding, + 105, 105, + 100, + 0, 2 * uiPi, + 0); + uiDrawPathEnd(winding); + + d2dClear(p, d2dWhite, 1.0); + + // TODO grid + + // TODO the example doesn't provide these + d2dSolidBrush(&fill, d2dForestGreen, 1.0); + d2dSolidBrush(&stroke, d2dCornflowerBlue, 1.0); + + sp.Thickness = 1.0; + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + + uiDrawFill(p->Context, alternate, &fill); + uiDrawStroke(p->Context, alternate, &stroke, &sp); + // TODO text + + uiDrawMatrixSetIdentity(&m); + uiDrawMatrixTranslate(&m, 300, 0); + uiDrawTransform(p->Context, &m); + uiDrawFill(p->Context, winding, &fill); + uiDrawStroke(p->Context, winding, &stroke, &sp); +// // TODO text + + uiDrawFreePath(winding); + uiDrawFreePath(alternate); +} + +// TODO https://msdn.microsoft.com/en-us/library/windows/desktop/dd756676%28v=vs.85%29.aspx + +// TODO? https://msdn.microsoft.com/en-us/library/windows/desktop/dd370971%28v=vs.85%29.aspx + +// TODO are there even examples here? https://msdn.microsoft.com/en-us/library/windows/desktop/dd370966%28v=vs.85%29.aspx + +// from https://msdn.microsoft.com/en-us/library/windows/desktop/dd756687%28v=vs.85%29.aspx +static void drawD2DRotate(uiAreaDrawParams *p) +{ + uiDrawPath *path; + uiDrawBrush original; + uiDrawBrush fill; + uiDrawBrush transform; + uiDrawStrokeParams originalsp; + uiDrawStrokeParams transformsp; + uiDrawMatrix m; + + originalsp.Dashes = NULL; + originalsp.NumDashes = 0; + originalsp.DashPhase = 0; + transformsp.Dashes = NULL; + transformsp.NumDashes = 0; + transformsp.DashPhase = 0; + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathAddRectangle(path, 438.0, 301.5, 498.0 - 438.0, 361.5 - 301.5); + uiDrawPathEnd(path); + + // TODO the example doesn't specify what these should be + d2dSolidBrush(&original, d2dBlack, 1.0); + d2dSolidBrush(&fill, d2dWhite, 0.5); + d2dSolidBrush(&transform, d2dForestGreen, 1.0); + // TODO this needs to be dashed + originalsp.Thickness = 1.0; + originalsp.Cap = uiDrawLineCapFlat; + originalsp.Join = uiDrawLineJoinMiter; + originalsp.MiterLimit = uiDrawDefaultMiterLimit; + transformsp.Thickness = 1.0; + transformsp.Cap = uiDrawLineCapFlat; + transformsp.Join = uiDrawLineJoinMiter; + transformsp.MiterLimit = uiDrawDefaultMiterLimit; + + // save for when we do the translated one + uiDrawSave(p->Context); + + uiDrawStroke(p->Context, path, &original, &originalsp); + + uiDrawMatrixSetIdentity(&m); + uiDrawMatrixRotate(&m, + 468.0, 331.5, + 45.0 * (uiPi / 180)); + uiDrawTransform(p->Context, &m); + + uiDrawFill(p->Context, path, &fill); + uiDrawStroke(p->Context, path, &transform, &transformsp); + + uiDrawRestore(p->Context); + + // translate to test the corner axis + uiDrawMatrixSetIdentity(&m); + uiDrawMatrixTranslate(&m, -200, -200); + uiDrawTransform(p->Context, &m); + + uiDrawStroke(p->Context, path, &original, &originalsp); + + uiDrawMatrixSetIdentity(&m); + uiDrawMatrixRotate(&m, + 438.0, 301.5, + 45.0 * (uiPi / 180)); + uiDrawTransform(p->Context, &m); + + uiDrawFill(p->Context, path, &fill); + uiDrawStroke(p->Context, path, &transform, &transformsp); + + uiDrawFreePath(path); +} + +// from https://msdn.microsoft.com/en-us/library/windows/desktop/dd756688%28v=vs.85%29.aspx +static void drawD2DScale(uiAreaDrawParams *p) +{ + uiDrawPath *path; + uiDrawBrush original; + uiDrawBrush fill; + uiDrawBrush transform; + uiDrawStrokeParams originalsp; + uiDrawStrokeParams transformsp; + uiDrawMatrix m; + + originalsp.Dashes = NULL; + originalsp.NumDashes = 0; + originalsp.DashPhase = 0; + transformsp.Dashes = NULL; + transformsp.NumDashes = 0; + transformsp.DashPhase = 0; + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathAddRectangle(path, 438.0, 80.5, 498.0 - 438.0, 140.5 - 80.5); + uiDrawPathEnd(path); + + // TODO the example doesn't specify what these should be + d2dSolidBrush(&original, d2dBlack, 1.0); + d2dSolidBrush(&fill, d2dWhite, 0.5); + d2dSolidBrush(&transform, d2dForestGreen, 1.0); + // TODO this needs to be dashed + originalsp.Thickness = 1.0; + originalsp.Cap = uiDrawLineCapFlat; + originalsp.Join = uiDrawLineJoinMiter; + originalsp.MiterLimit = uiDrawDefaultMiterLimit; + transformsp.Thickness = 1.0; + transformsp.Cap = uiDrawLineCapFlat; + transformsp.Join = uiDrawLineJoinMiter; + transformsp.MiterLimit = uiDrawDefaultMiterLimit; + + // save for when we do the translated one + uiDrawSave(p->Context); + + uiDrawStroke(p->Context, path, &original, &originalsp); + + uiDrawMatrixSetIdentity(&m); + uiDrawMatrixScale(&m, + 438.0, 80.5, + 1.3, 1.3); + uiDrawTransform(p->Context, &m); + + uiDrawFill(p->Context, path, &fill); + uiDrawStroke(p->Context, path, &transform, &transformsp); + + uiDrawRestore(p->Context); + + // for testing purposes, show what happens if we scale about (0, 0) + uiDrawMatrixSetIdentity(&m); + uiDrawMatrixTranslate(&m, -300, 50); + uiDrawTransform(p->Context, &m); + + uiDrawStroke(p->Context, path, &original, &originalsp); + + uiDrawMatrixSetIdentity(&m); + uiDrawMatrixScale(&m, + 0, 0, + 1.3, 1.3); + uiDrawTransform(p->Context, &m); + + uiDrawFill(p->Context, path, &fill); + uiDrawStroke(p->Context, path, &transform, &transformsp); + + uiDrawFreePath(path); +} + +// from https://msdn.microsoft.com/en-us/library/windows/desktop/dd756689%28v=vs.85%29.aspx +// TODO counterclockwise?! +void drawD2DSkew(uiAreaDrawParams *p) +{ + uiDrawPath *path; + uiDrawBrush original; + uiDrawBrush fill; + uiDrawBrush transform; + uiDrawStrokeParams originalsp; + uiDrawStrokeParams transformsp; + uiDrawMatrix m; + + originalsp.Dashes = NULL; + originalsp.NumDashes = 0; + originalsp.DashPhase = 0; + transformsp.Dashes = NULL; + transformsp.NumDashes = 0; + transformsp.DashPhase = 0; + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathAddRectangle(path, 126.0, 301.5, 186.0 - 126.0, 361.5 - 301.5); + uiDrawPathEnd(path); + + // TODO the example doesn't specify what these should be + d2dSolidBrush(&original, d2dBlack, 1.0); + d2dSolidBrush(&fill, d2dWhite, 0.5); + d2dSolidBrush(&transform, d2dForestGreen, 1.0); + // TODO this needs to be dashed + originalsp.Thickness = 1.0; + originalsp.Cap = uiDrawLineCapFlat; + originalsp.Join = uiDrawLineJoinMiter; + originalsp.MiterLimit = uiDrawDefaultMiterLimit; + transformsp.Thickness = 1.0; + transformsp.Cap = uiDrawLineCapFlat; + transformsp.Join = uiDrawLineJoinMiter; + transformsp.MiterLimit = uiDrawDefaultMiterLimit; + + // save for when we do the translated one + uiDrawSave(p->Context); + + uiDrawStroke(p->Context, path, &original, &originalsp); + + uiDrawMatrixSetIdentity(&m); + uiDrawMatrixSkew(&m, + 126.0, 301.5, + 45.0 * (uiPi / 180), 0); + uiDrawTransform(p->Context, &m); + + uiDrawFill(p->Context, path, &fill); + uiDrawStroke(p->Context, path, &transform, &transformsp); + + uiDrawRestore(p->Context); + + // for testing purposes, show what happens if we skew about (0, 0) + uiDrawMatrixSetIdentity(&m); + uiDrawMatrixTranslate(&m, 0, -200); + uiDrawTransform(p->Context, &m); + + uiDrawStroke(p->Context, path, &original, &originalsp); + + uiDrawMatrixSetIdentity(&m); + uiDrawMatrixSkew(&m, + 0, 0, + 45.0 * (uiPi / 180), 0); + uiDrawTransform(p->Context, &m); + + uiDrawFill(p->Context, path, &fill); + uiDrawStroke(p->Context, path, &transform, &transformsp); + + uiDrawFreePath(path); +} + +// from https://msdn.microsoft.com/en-us/library/windows/desktop/dd756691%28v=vs.85%29.aspx +static void drawD2DTranslate(uiAreaDrawParams *p) +{ + uiDrawPath *path; + uiDrawBrush original; + uiDrawBrush fill; + uiDrawBrush transform; + uiDrawStrokeParams originalsp; + uiDrawStrokeParams transformsp; + uiDrawMatrix m; + + originalsp.Dashes = NULL; + originalsp.NumDashes = 0; + originalsp.DashPhase = 0; + transformsp.Dashes = NULL; + transformsp.NumDashes = 0; + transformsp.DashPhase = 0; + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathAddRectangle(path, 126.0, 80.5, 186.0 - 126.0, 140.5 - 80.5); + uiDrawPathEnd(path); + + // TODO the example doesn't specify what these should be + d2dSolidBrush(&original, d2dBlack, 1.0); + d2dSolidBrush(&fill, d2dWhite, 0.5); + d2dSolidBrush(&transform, d2dForestGreen, 1.0); + // TODO this needs to be dashed + originalsp.Thickness = 1.0; + originalsp.Cap = uiDrawLineCapFlat; + originalsp.Join = uiDrawLineJoinMiter; + originalsp.MiterLimit = uiDrawDefaultMiterLimit; + transformsp.Thickness = 1.0; + transformsp.Cap = uiDrawLineCapFlat; + transformsp.Join = uiDrawLineJoinMiter; + transformsp.MiterLimit = uiDrawDefaultMiterLimit; + + uiDrawStroke(p->Context, path, &original, &originalsp); + + uiDrawMatrixSetIdentity(&m); + uiDrawMatrixTranslate(&m, 20, 10); + uiDrawTransform(p->Context, &m); + + uiDrawFill(p->Context, path, &fill); + uiDrawStroke(p->Context, path, &transform, &transformsp); + + uiDrawFreePath(path); +} + +// from https://msdn.microsoft.com/en-us/library/windows/desktop/dd756672%28v=vs.85%29.aspx +// TODO the points seem off +static void drawD2DMultiTransforms(uiAreaDrawParams *p) +{ + uiDrawPath *path; + uiDrawBrush original; + uiDrawBrush fill; + uiDrawBrush transform; + uiDrawStrokeParams originalsp; + uiDrawStrokeParams transformsp; + uiDrawMatrix mtranslate; + uiDrawMatrix mrotate; + + originalsp.Dashes = NULL; + originalsp.NumDashes = 0; + originalsp.DashPhase = 0; + transformsp.Dashes = NULL; + transformsp.NumDashes = 0; + transformsp.DashPhase = 0; + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathAddRectangle(path, 300.0, 40.0, 360.0 - 300.0, 100.0 - 40.0); + uiDrawPathEnd(path); + + // TODO the example doesn't specify what these should be + d2dSolidBrush(&original, d2dBlack, 1.0); + d2dSolidBrush(&fill, d2dWhite, 0.5); + d2dSolidBrush(&transform, d2dForestGreen, 1.0); + // TODO this needs to be dashed + originalsp.Thickness = 1.0; + originalsp.Cap = uiDrawLineCapFlat; + originalsp.Join = uiDrawLineJoinMiter; + originalsp.MiterLimit = uiDrawDefaultMiterLimit; + transformsp.Thickness = 1.0; + transformsp.Cap = uiDrawLineCapFlat; + transformsp.Join = uiDrawLineJoinMiter; + transformsp.MiterLimit = uiDrawDefaultMiterLimit; + + uiDrawMatrixSetIdentity(&mtranslate); + uiDrawMatrixTranslate(&mtranslate, 20.0, 10.0); + uiDrawMatrixSetIdentity(&mrotate); + uiDrawMatrixRotate(&mrotate, + 330.0, 70.0, + 45.0 * (uiPi / 180)); + + // save for when we do the opposite one + uiDrawSave(p->Context); + + uiDrawStroke(p->Context, path, &original, &originalsp); + + uiDrawTransform(p->Context, &mrotate); + uiDrawTransform(p->Context, &mtranslate); + + uiDrawFill(p->Context, path, &fill); + uiDrawStroke(p->Context, path, &transform, &transformsp); + + uiDrawRestore(p->Context); + uiDrawFreePath(path); + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathAddRectangle(path, 40.0, 40.0, 100.0 - 40.0, 100.0 - 40.0); + uiDrawPathEnd(path); + + uiDrawMatrixSetIdentity(&mtranslate); + uiDrawMatrixTranslate(&mtranslate, 20.0, 10.0); + uiDrawMatrixSetIdentity(&mrotate); + uiDrawMatrixRotate(&mrotate, + 70.0, 70.0, + 45.0 * (uiPi / 180)); + + uiDrawStroke(p->Context, path, &original, &originalsp); + + uiDrawTransform(p->Context, &mtranslate); + uiDrawTransform(p->Context, &mrotate); + + uiDrawFill(p->Context, path, &fill); + uiDrawStroke(p->Context, path, &transform, &transformsp); + + uiDrawFreePath(path); +} + +// TODO https://msdn.microsoft.com/en-us/library/windows/desktop/dd756675%28v=vs.85%29.aspx + +// TODO https://msdn.microsoft.com/en-us/library/windows/desktop/dd756673%28v=vs.85%29.aspx + +// TODO https://msdn.microsoft.com/en-us/library/windows/desktop/dd756684%28v=vs.85%29.aspx + +// TODO dashing https://msdn.microsoft.com/en-us/library/windows/desktop/dd756683%28v=vs.85%29.aspx + +// from https://msdn.microsoft.com/en-us/library/windows/desktop/dd756682%28v=vs.85%29.aspx +static void drawD2DComplexShape(uiAreaDrawParams *p) +{ + uiDrawPath *path; + uiDrawBrush black; + uiDrawBrush gradient; + uiDrawBrushGradientStop stops[2]; + uiDrawStrokeParams sp; + uiDrawMatrix m; + + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, 0, 0); + uiDrawPathLineTo(path, 200, 0); + uiDrawPathBezierTo(path, + 150, 50, + 150, 150, + 200, 200); + uiDrawPathLineTo(path, 0, 200); + uiDrawPathBezierTo(path, + 50, 150, + 50, 50, + 0, 0); + uiDrawPathCloseFigure(path); + uiDrawPathEnd(path); + + d2dSolidBrush(&black, d2dBlack, 1.0); + + stops[0].Pos =0.0; + stops[0].R = 0.0; + stops[0].G = 1.0; + stops[0].B = 1.0; + stops[0].A = 0.25; + stops[1].Pos = 1.0; + stops[1].R = 0.0; + stops[1].G = 0.0; + stops[1].B = 1.0; + stops[1].A = 1.0; + gradient.Type = uiDrawBrushTypeLinearGradient; + gradient.X0 = 100; + gradient.Y0 = 0; + gradient.X1 = 100; + gradient.Y1 = 200; + gradient.Stops = stops; + gradient.NumStops = 2; + + uiDrawMatrixSetIdentity(&m); + uiDrawMatrixTranslate(&m, 20, 20); + uiDrawTransform(p->Context, &m); + + sp.Thickness = 10.0; + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + + uiDrawStroke(p->Context, path, &black, &sp); + uiDrawFill(p->Context, path, &gradient); + + uiDrawFreePath(path); +} + +// TODO https://msdn.microsoft.com/en-us/library/windows/desktop/dd756692%28v=vs.85%29.aspx + +// TODO https://msdn.microsoft.com/en-us/library/windows/desktop/dd756686%28v=vs.85%29.aspx + +// TODO https://msdn.microsoft.com/en-us/library/windows/desktop/dd756685%28v=vs.85%29.aspx + +// TODO https://msdn.microsoft.com/en-us/library/windows/desktop/dd756674%28v=vs.85%29.aspx + +// TODO? https://msdn.microsoft.com/en-us/library/windows/desktop/ee329947%28v=vs.85%29.aspx + +// TODO https://msdn.microsoft.com/en-us/library/windows/desktop/ff485857%28v=vs.85%29.aspx + +// TODO? https://msdn.microsoft.com/en-us/library/windows/desktop/dd756755%28v=vs.85%29.aspx + +// TODO go through the API reference and spot examples that aren't listed + +// TODO all of these https://msdn.microsoft.com/en-us/library/windows/desktop/dd368187%28v=vs.85%29.aspx + +// cairo Samples Page (http://cairographics.org/samples/) + +static void crsourcergba(uiDrawBrush *brush, double r, double g, double b, double a) +{ + brush->Type = uiDrawBrushTypeSolid; + brush->R = r; + brush->G = g; + brush->B = b; + brush->A = a; +} + +// arc +static void drawCSArc(uiAreaDrawParams *p) +{ + double xc = 128.0; + double yc = 128.0; + double radius = 100.0; + double angle1 = 45.0 * (uiPi / 180.0); + double angle2 = 180.0 * (uiPi / 180.0); + uiDrawBrush source; + uiDrawStrokeParams sp; + uiDrawPath *path; + + crsourcergba(&source, 0, 0, 0, 1); + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + sp.Thickness = 10.0; + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigureWithArc(path, + xc, yc, + radius, + angle1, + angle2 - angle1, + 0); + uiDrawPathEnd(path); + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); + + crsourcergba(&source, 1, 0.2, 0.2, 0.6); + sp.Thickness = 6.0; + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigureWithArc(path, + xc, yc, + 10.0, + 0, 2 * uiPi, + 0); + uiDrawPathEnd(path); + uiDrawFill(p->Context, path, &source); + uiDrawFreePath(path); + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigureWithArc(path, + xc, yc, + radius, + angle1, 0, + 0); + uiDrawPathLineTo(path, xc, yc); + uiDrawPathNewFigureWithArc(path, + xc, yc, + radius, + angle2, 0, + 0); + uiDrawPathLineTo(path, xc, yc); + uiDrawPathEnd(path); + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); +} + +// arc negative +static void drawCSArcNegative(uiAreaDrawParams *p) +{ + double xc = 128.0; + double yc = 128.0; + double radius = 100.0; + double angle1 = 45.0 * (uiPi / 180.0); + double angle2 = 180.0 * (uiPi / 180.0); + uiDrawBrush source; + uiDrawStrokeParams sp; + uiDrawPath *path; + + crsourcergba(&source, 0, 0, 0, 1); + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + sp.Thickness = 10.0; + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigureWithArc(path, + xc, yc, + radius, + angle1, + angle2 - angle1, + 1); + uiDrawPathEnd(path); + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); + + crsourcergba(&source, 1, 0.2, 0.2, 0.6); + sp.Thickness = 6.0; + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigureWithArc(path, + xc, yc, + 10.0, + 0, 2 * uiPi, + 0); + uiDrawPathEnd(path); + uiDrawFill(p->Context, path, &source); + uiDrawFreePath(path); + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigureWithArc(path, + xc, yc, + radius, + angle1, 0, + 0); + uiDrawPathLineTo(path, xc, yc); + uiDrawPathNewFigureWithArc(path, + xc, yc, + radius, + angle2, 0, + 0); + uiDrawPathLineTo(path, xc, yc); + uiDrawPathEnd(path); + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); +} + +// clip +static void drawCSClip(uiAreaDrawParams *p) +{ + uiDrawBrush source; + uiDrawStrokeParams sp; + uiDrawPath *path; + + crsourcergba(&source, 0, 0, 0, 1); + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + path = uiDrawNewPath(uiDrawFillModeWinding); + + uiDrawPathNewFigureWithArc(path, + 128.0, 128.0, + 76.8, + 0, 2 * uiPi, + 0); + uiDrawPathEnd(path); + uiDrawClip(p->Context, path); + uiDrawFreePath(path); + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathAddRectangle(path, 0, 0, 256, 256); + uiDrawPathEnd(path); + uiDrawFill(p->Context, path, &source); + uiDrawFreePath(path); + + crsourcergba(&source, 0, 1, 0, 1); + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, 0, 0); + uiDrawPathLineTo(path, 256, 256); + uiDrawPathNewFigure(path, 256, 0); + uiDrawPathLineTo(path, 0, 256); + uiDrawPathEnd(path); + sp.Thickness = 10.0; + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); +} + +// TODO clip image + +// curve rectangle +static void drawCSCurveRectangle(uiAreaDrawParams *p) +{ + double x0 = 25.6, /* parameters like cairo_rectangle */ + y0 = 25.6, + rect_width = 204.8, + rect_height = 204.8, + radius = 102.4; /* and an approximate curvature radius */ + + double x1,y1; + + uiDrawBrush source; + uiDrawStrokeParams sp; + uiDrawPath *path; + + crsourcergba(&source, 0, 0, 0, 1); + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + path = uiDrawNewPath(uiDrawFillModeWinding); + + x1=x0+rect_width; + y1=y0+rect_height; + if (!rect_width || !rect_height) + return; + if (rect_width/2 < radius) { + if (rect_height/2Context, path, &source); + crsourcergba(&source, 0.5, 0, 0, 0.5); + sp.Thickness = 10.0; + uiDrawStroke(p->Context, path, &source, &sp); + + uiDrawFreePath(path); +} + +// curve to +static void drawCSCurveTo(uiAreaDrawParams *p) +{ + double x=25.6, y=128.0; + double x1=102.4, y1=230.4, + x2=153.6, y2=25.6, + x3=230.4, y3=128.0; + uiDrawBrush source; + uiDrawStrokeParams sp; + uiDrawPath *path; + + crsourcergba(&source, 0, 0, 0, 1); + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + path = uiDrawNewPath(uiDrawFillModeWinding); + + uiDrawPathNewFigure(path, x, y); + uiDrawPathBezierTo(path, x1, y1, x2, y2, x3, y3); + uiDrawPathEnd(path); + sp.Thickness = 10.0; + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); + + crsourcergba(&source, 1, 0.2, 0.2, 0.6); + sp.Thickness = 6.0; + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, x, y); + uiDrawPathLineTo(path, x1, y1); + uiDrawPathNewFigure(path, x2, y2); + uiDrawPathLineTo(path, x3, y3); + uiDrawPathEnd(path); + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); +} + +// dash +static void drawCSDash(uiAreaDrawParams *p) +{ + double dashes[] = { + 50.0, /* ink */ + 10.0, /* skip */ + 10.0, /* ink */ + 10.0 /* skip*/ + }; + int ndash = sizeof (dashes)/sizeof(dashes[0]); + double offset = -50.0; + + uiDrawBrush source; + uiDrawStrokeParams sp; + uiDrawPath *path; + + crsourcergba(&source, 0, 0, 0, 1); + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + sp.Dashes = dashes; + sp.NumDashes = ndash; + sp.DashPhase = offset; + sp.Thickness = 10.0; + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, 128.0, 25.6); + uiDrawPathLineTo(path, 230.4, 230.4); + uiDrawPathLineTo(path, 230.4 -102.4, 230.4 + 0.0); + uiDrawPathBezierTo(path, + 51.2, 230.4, + 51.2, 128.0, + 128.0, 128.0); + uiDrawPathEnd(path); + + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); +} + +// fill and stroke2 +static void drawCSFillAndStroke2(uiAreaDrawParams *p) +{ + uiDrawBrush source; + uiDrawStrokeParams sp; + uiDrawPath *path; + + crsourcergba(&source, 0, 0, 0, 1); + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + path = uiDrawNewPath(uiDrawFillModeWinding); + + uiDrawPathNewFigure(path, 128.0, 25.6); + uiDrawPathLineTo(path, 230.4, 230.4); + uiDrawPathLineTo(path, 230.4 - 102.4, 230.4 + 0.0); + uiDrawPathBezierTo(path, 51.2, 230.4, 51.2, 128.0, 128.0, 128.0); + uiDrawPathCloseFigure(path); + + uiDrawPathNewFigure(path, 64.0, 25.6); + uiDrawPathLineTo(path, 64.0 + 51.2, 25.6 + 51.2); + uiDrawPathLineTo(path, 64.0 + 51.2 -51.2, 25.6 + 51.2 + 51.2); + uiDrawPathLineTo(path, 64.0 + 51.2 -51.2 -51.2, 25.6 + 51.2 + 51.2 -51.2); + uiDrawPathCloseFigure(path); + + uiDrawPathEnd(path); + + sp.Thickness = 10.0; + crsourcergba(&source, 0, 0, 1, 1); + uiDrawFill(p->Context, path, &source); + crsourcergba(&source, 0, 0, 0, 1); + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); +} + +// fill style +static void drawCSFillStyle(uiAreaDrawParams *p) +{ + uiDrawBrush source; + uiDrawStrokeParams sp; + uiDrawPath *path; + uiDrawMatrix m; + + crsourcergba(&source, 0, 0, 0, 1); + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + sp.Thickness = 6; + + path = uiDrawNewPath(uiDrawFillModeAlternate); + uiDrawPathAddRectangle(path, 12, 12, 232, 70); + uiDrawPathNewFigureWithArc(path, + 64, 64, + 40, + 0, 2*uiPi, + 0); + uiDrawPathNewFigureWithArc(path, + 192, 64, + 40, + 0, -2*uiPi, + 1); + uiDrawPathEnd(path); + + crsourcergba(&source, 0, 0.7, 0, 1); + uiDrawFill(p->Context, path, &source); + crsourcergba(&source, 0, 0, 0, 1); + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); + + uiDrawMatrixSetIdentity(&m); + uiDrawMatrixTranslate(&m, 0, 128); + uiDrawTransform(p->Context, &m); + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathAddRectangle(path, 12, 12, 232, 70); + uiDrawPathNewFigureWithArc(path, + 64, 64, + 40, + 0, 2*uiPi, + 0); + uiDrawPathNewFigureWithArc(path, + 192, 64, + 40, + 0, -2*uiPi, + 1); + uiDrawPathEnd(path); + + crsourcergba(&source, 0, 0, 0.9, 1); + uiDrawFill(p->Context, path, &source); + crsourcergba(&source, 0, 0, 0, 1); + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); +} + +// TOOD gradient (radial gradient with two circles) + +// TODO image + +// TODO imagepattern + +// multi segment caps +static void drawCSMultiCaps(uiAreaDrawParams *p) +{ + uiDrawBrush source; + uiDrawStrokeParams sp; + uiDrawPath *path; + + crsourcergba(&source, 0, 0, 0, 1); + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + path = uiDrawNewPath(uiDrawFillModeWinding); + + uiDrawPathNewFigure(path, 50.0, 75.0); + uiDrawPathLineTo(path, 200.0, 75.0); + + uiDrawPathNewFigure(path, 50.0, 125.0); + uiDrawPathLineTo(path, 200.0, 125.0); + + uiDrawPathNewFigure(path, 50.0, 175.0); + uiDrawPathLineTo(path, 200.0, 175.0); + uiDrawPathEnd(path); + + sp.Thickness = 30.0; + sp.Cap = uiDrawLineCapRound; + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); +} + +// rounded rectangle +static void drawCSRoundRect(uiAreaDrawParams *p) +{ + double x = 25.6, /* parameters like cairo_rectangle */ + y = 25.6, + width = 204.8, + height = 204.8, + aspect = 1.0, /* aspect ratio */ + corner_radius = height / 10.0; /* and corner curvature radius */ + + double radius = corner_radius / aspect; + double degrees = uiPi / 180.0; + + uiDrawBrush source; + uiDrawStrokeParams sp; + uiDrawPath *path; + + crsourcergba(&source, 0, 0, 0, 1); + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + path = uiDrawNewPath(uiDrawFillModeWinding); + + // top right corner + uiDrawPathNewFigureWithArc(path, + x + width - radius, y + radius, + radius, + -90 * degrees, uiPi / 2, + 0); + // bottom right corner + uiDrawPathArcTo(path, + x + width - radius, y + height - radius, + radius, + 0 * degrees, uiPi / 2, + 0); + // bottom left corner + uiDrawPathArcTo(path, + x + radius, y + height - radius, + radius, + 90 * degrees, uiPi / 2, + 0); + // top left corner + uiDrawPathArcTo(path, + x + radius, y + radius, + radius, + 180 * degrees, uiPi / 2, + 0); + uiDrawPathCloseFigure(path); + uiDrawPathEnd(path); + + crsourcergba(&source, 0.5, 0.5, 1, 1); + uiDrawFill(p->Context, path, &source); + crsourcergba(&source, 0.5, 0, 0, 0.5); + sp.Thickness = 10.0; + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); +} + +// set line cap +static void drawCSSetLineCap(uiAreaDrawParams *p) +{ + uiDrawBrush source; + uiDrawStrokeParams sp; + uiDrawPath *path; + + crsourcergba(&source, 0, 0, 0, 1); + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + sp.Thickness = 30.0; + + sp.Cap = uiDrawLineCapFlat; + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, 64.0, 50.0); + uiDrawPathLineTo(path, 64.0, 200.0); + uiDrawPathEnd(path); + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); + + sp.Cap = uiDrawLineCapRound; + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, 128.0, 50.0); + uiDrawPathLineTo(path, 128.0, 200.0); + uiDrawPathEnd(path); + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); + + sp.Cap = uiDrawLineCapSquare; + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, 192.0, 50.0); + uiDrawPathLineTo(path, 192.0, 200.0); + uiDrawPathEnd(path); + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); + + // draw helping lines + // keep the square cap to match the reference picture on the cairo website + crsourcergba(&source, 1, 0.2, 0.2, 1); + sp.Thickness = 2.56; + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, 64.0, 50.0); + uiDrawPathLineTo(path, 64.0, 200.0); + uiDrawPathNewFigure(path, 128.0, 50.0); + uiDrawPathLineTo(path, 128.0, 200.0); + uiDrawPathNewFigure(path, 192.0, 50.0); + uiDrawPathLineTo(path, 192.0, 200.0); + uiDrawPathEnd(path); + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); +} + +// set line join +static void drawCSSetLineJoin(uiAreaDrawParams *p) +{ + uiDrawBrush source; + uiDrawStrokeParams sp; + uiDrawPath *path; + + crsourcergba(&source, 0, 0, 0, 1); + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + sp.Thickness = 40.96; + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, 76.8, 84.48); + uiDrawPathLineTo(path, 76.8 + 51.2, 84.48 -51.2); + uiDrawPathLineTo(path, 76.8 + 51.2 + 51.2, 84.48 - 51.2 + 51.2); + uiDrawPathEnd(path); + sp.Join = uiDrawLineJoinMiter; + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, 76.8, 161.28); + uiDrawPathLineTo(path, 76.8 + 51.2, 161.28 -51.2); + uiDrawPathLineTo(path, 76.8 + 51.2 + 51.2, 161.28 - 51.2 + 51.2); + uiDrawPathEnd(path); + sp.Join = uiDrawLineJoinBevel; + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, 76.8, 238.08); + uiDrawPathLineTo(path, 76.8 + 51.2, 238.08 -51.2); + uiDrawPathLineTo(path, 76.8 + 51.2 + 51.2, 238.08 - 51.2 + 51.2); + uiDrawPathEnd(path); + sp.Join = uiDrawLineJoinRound; + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); +} + +// TODO text + +// TODO text align center + +// TODO text extents + +// Quartz 2D Programming Guide + +static void cgaddrect(uiDrawPath *path, uiAreaDrawParams *p, double x, double y, double width, double height) +{ + uiDrawPathAddRectangle(path, + x, p->AreaHeight - y - height, + width, height); +} + +// Graphics Contexts > Creating a Window Graphics Context in Mac OS X +static void drawQ2DCreateWindowGC(uiAreaDrawParams *p) +{ + uiDrawPath *path; + uiDrawBrush brush; + + crsourcergba(&brush, 1, 0, 0, 1); + path = uiDrawNewPath(uiDrawFillModeWinding); + cgaddrect(path, p, 0, 0, 200, 100); + uiDrawPathEnd(path); + uiDrawFill(p->Context, path, &brush); + uiDrawFreePath(path); + + crsourcergba(&brush, 0, 0, 1, .5); + path = uiDrawNewPath(uiDrawFillModeWinding); + cgaddrect(path, p, 0, 0, 100, 200); + uiDrawPathEnd(path); + uiDrawFill(p->Context, path, &brush); + uiDrawFreePath(path); +} + +// TODO Patterns page? + +// TODO Shadows page? + +// TODO Gradients page (includes some circle-circle radial gradients) + +// TODO Transparency Layers page? + +// TODO Core Graphics Layer Drawing page? + +// Cocoa Drawing Guide + +// TODO Advanced Drawing Techniques page? + +// TODO Text page, if any? + +static const struct drawtest tests[] = { + { "Original uiArea test", drawOriginal }, + { "Arc test", drawArcs }, + { "Direct2D: Direct2D Quickstart for Windows 8", drawD2DW8QS }, + { "Direct2D: Creating a Simple Direct2D Application", drawD2DSimpleApp }, + { "Direct2D: How to Create a Solid Color Brush", drawD2DSolidBrush }, + { "Direct2D: How to Create a Linear Gradient Brush", drawD2DLinearBrush }, + { "Direct2D: How to Create a Radial Gradient Brush", drawD2DRadialBrush }, + { "Direct2D: Path Geometries Overview", drawD2DPathGeometries }, + { "Direct2D: How to Create Geometry Groups", drawD2DGeometryGroup }, + { "Direct2D: How to Rotate an Object", drawD2DRotate }, + { "Direct2D: How to Scale an Object", drawD2DScale }, + { "Direct2D: How to Skew an Object", drawD2DSkew }, + { "Direct2D: How to Translate an Object", drawD2DTranslate }, + { "Direct2D: How to Apply Multiple Transforms to an Object", drawD2DMultiTransforms }, + { "Direct2D: How to Draw and Fill a Complex Shape", drawD2DComplexShape }, + { "cairo samples: arc", drawCSArc }, + { "cairo samples: arc negative", drawCSArcNegative }, + { "cairo samples: clip", drawCSClip }, + { "cairo samples: curve rectangle", drawCSCurveRectangle }, + { "cairo samples: curve to", drawCSCurveTo }, + { "cairo samples: dash", drawCSDash }, + { "cairo samples: fill and stroke2", drawCSFillAndStroke2 }, + { "cairo samples: fill style", drawCSFillStyle }, + { "cairo samples: multi segment caps", drawCSMultiCaps }, + { "cairo samples: rounded rectangle", drawCSRoundRect }, + { "cairo samples: set line cap", drawCSSetLineCap }, + { "cairo samples: set line join", drawCSSetLineJoin }, + { "Quartz 2D PG: Creating a Window Graphics Context in Mac OS X", drawQ2DCreateWindowGC }, + { NULL, NULL }, +}; + +void runDrawTest(int n, uiAreaDrawParams *p) +{ + (*(tests[n].draw))(p); +} + +void populateComboboxWithTests(uiCombobox *c) +{ + size_t i; + + for (i = 0; tests[i].name != NULL; i++) + uiComboboxAppend(c, tests[i].name); +} diff --git a/dep/libui/test/images.c b/dep/libui/test/images.c new file mode 100644 index 0000000..31107f7 --- /dev/null +++ b/dep/libui/test/images.c @@ -0,0 +1,682 @@ +// auto-generated by images/gen.go +#include "test.h" + +static const uint8_t dat0[] = { + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xE5, 0x60, 0xFC, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xE5, 0x60, 0xFC, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xE5, 0x60, 0xFC, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xE5, 0x60, 0xFC, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, + 0x8A, 0xC3, 0xFF, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, +}; + +static const uint8_t dat1[] = { + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xE5, 0x60, 0xFC, 0xFF, + 0xE5, 0x60, 0xFC, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xE5, 0x60, 0xFC, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xE5, 0x60, 0xFC, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xE5, 0x60, 0xFC, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xE5, 0x60, 0xFC, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xE5, 0x60, 0xFC, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xE5, 0x60, 0xFC, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xE5, 0x60, 0xFC, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xE5, 0x60, 0xFC, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xE5, 0x60, 0xFC, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xE5, 0x60, 0xFC, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xE5, 0x60, 0xFC, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xE5, 0x60, 0xFC, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xE5, 0x60, 0xFC, 0xFF, + 0xE5, 0x60, 0xFC, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, + 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0x40, 0x79, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, + 0x8A, 0xC3, 0xFF, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0x8A, 0xC3, 0xFF, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0x8A, 0xC3, 0xFF, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, + 0xFF, 0xFB, 0x43, 0xFF, 0xFF, 0xFB, 0x43, 0xFF, 0x8A, 0xC3, 0xFF, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, + 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, 0x89, 0xC5, 0x7C, 0xFF, +}; + +static const uint8_t dat2[] = { + 0x67, 0x67, 0x67, 0xAC, 0x81, 0x81, 0x81, 0xFF, 0x81, 0x81, 0x81, 0xFF, 0x81, 0x81, 0x81, 0xFF, + 0x81, 0x81, 0x81, 0xFF, 0x81, 0x81, 0x81, 0xFF, 0x81, 0x81, 0x81, 0xFF, 0x81, 0x81, 0x81, 0xFF, + 0x81, 0x81, 0x81, 0xFF, 0x81, 0x81, 0x81, 0xFF, 0x81, 0x81, 0x81, 0xFF, 0x81, 0x81, 0x81, 0xFF, + 0x81, 0x81, 0x81, 0xFF, 0x2B, 0x2B, 0x2B, 0x56, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x81, 0x81, 0x81, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0x81, 0x81, 0x81, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x81, 0x81, 0x81, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xB7, 0xB7, 0xB7, 0xFF, 0xB7, 0xB7, 0xB7, 0xFF, + 0xB7, 0xB7, 0xB8, 0xFF, 0x9E, 0x9E, 0x9F, 0xFF, 0xB8, 0xB8, 0xB8, 0xFF, 0xB8, 0xB8, 0xB8, 0xFF, + 0x9F, 0x9F, 0x9F, 0xFF, 0xB8, 0xB8, 0xB9, 0xFF, 0xB8, 0xB8, 0xB9, 0xFF, 0x9F, 0x9F, 0x9F, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0x81, 0x81, 0x81, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x81, 0x81, 0x81, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x9E, 0x9E, 0x9E, 0xFF, 0x9F, 0x9F, 0x9E, 0xFF, + 0x9F, 0x9F, 0x9F, 0xFF, 0x9F, 0x9F, 0x9F, 0xFF, 0x9F, 0x9F, 0x9F, 0xFF, 0x9F, 0x9F, 0x9F, 0xFF, + 0x9F, 0x9F, 0x9F, 0xFF, 0x9F, 0x9F, 0x9F, 0xFF, 0x9F, 0x9F, 0x9F, 0xFF, 0x9F, 0x9F, 0x9F, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0x81, 0x81, 0x81, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x81, 0x81, 0x81, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xB7, 0xB8, 0xB7, 0xFF, 0xC3, 0xC3, 0xC3, 0xFF, + 0xC3, 0xC3, 0xC3, 0xFF, 0x9F, 0x9F, 0x9F, 0xFF, 0xEE, 0xEE, 0xEE, 0xFF, 0xEE, 0xEE, 0xEE, 0xFF, + 0xC2, 0xC2, 0xC2, 0xFF, 0xEE, 0xEF, 0xEE, 0xFF, 0xEF, 0xEE, 0xEF, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0x81, 0x81, 0x81, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x81, 0x81, 0x81, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xB1, 0xB1, 0xB1, 0xFF, 0xB8, 0xB8, 0xB8, 0xFF, + 0xB9, 0xB8, 0xB9, 0xFF, 0x9F, 0x9F, 0x9F, 0xFF, 0xE0, 0xE0, 0xE0, 0xFF, 0xE0, 0xE1, 0xE0, 0xFF, + 0xC2, 0xC2, 0xC2, 0xFF, 0xE1, 0xE0, 0xE0, 0xFF, 0xE1, 0xE1, 0xE1, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0x81, 0x81, 0x81, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x81, 0x81, 0x81, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xB9, 0xB8, 0xB8, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF, + 0xC3, 0xC4, 0xC4, 0xFF, 0x9F, 0x9F, 0x9F, 0xFF, 0xEE, 0xEE, 0xEF, 0xFF, 0xEF, 0xEE, 0xEF, 0xFF, + 0xC2, 0xC2, 0xC2, 0xFF, 0xEF, 0xEF, 0xEF, 0xFF, 0xF0, 0xEF, 0xEF, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0x81, 0x81, 0x81, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x81, 0x81, 0x81, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xB1, 0xB1, 0xB1, 0xFF, 0xB9, 0xB9, 0xB8, 0xFF, + 0xB9, 0xB9, 0xB9, 0xFF, 0x9F, 0x9F, 0x9F, 0xFF, 0xC9, 0xA6, 0xA5, 0xFF, 0xAE, 0x3A, 0x36, 0xFF, + 0xA5, 0x0F, 0x0C, 0xFF, 0xA4, 0x02, 0x01, 0xFF, 0xA4, 0x02, 0x01, 0xFF, 0xA4, 0x0D, 0x0A, 0xFF, + 0xB0, 0x3B, 0x37, 0xFF, 0x8D, 0x69, 0x69, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x81, 0x81, 0x81, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xB9, 0xB9, 0xB9, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF, + 0xC4, 0xC4, 0xC4, 0xFF, 0x9E, 0x40, 0x3D, 0xFF, 0xA7, 0x0A, 0x07, 0xFF, 0xC6, 0x64, 0x53, 0xFF, + 0xCB, 0x71, 0x5C, 0xFF, 0xC9, 0x73, 0x5D, 0xFF, 0xC5, 0x71, 0x5B, 0xFF, 0xBF, 0x6C, 0x59, 0xFF, + 0xC0, 0x6E, 0x61, 0xFF, 0xAC, 0x20, 0x1D, 0xFF, 0x7E, 0x29, 0x27, 0xC1, 0x19, 0x19, 0x19, 0x19, + 0x81, 0x81, 0x81, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xB2, 0xB2, 0xB2, 0xFF, 0xB9, 0xB9, 0xB9, 0xFF, + 0xA6, 0x5C, 0x5B, 0xFF, 0xAF, 0x20, 0x17, 0xFF, 0xCB, 0x72, 0x5D, 0xFF, 0xC7, 0x65, 0x4D, 0xFF, + 0xBB, 0x53, 0x38, 0xFF, 0xB6, 0x51, 0x36, 0xFF, 0xB0, 0x4E, 0x35, 0xFF, 0xB3, 0x5D, 0x47, 0xFF, + 0xAE, 0x5B, 0x45, 0xFF, 0xA9, 0x57, 0x43, 0xFF, 0xAA, 0x2F, 0x28, 0xFF, 0x64, 0x17, 0x16, 0xA1, + 0x81, 0x81, 0x81, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xB9, 0xB9, 0xB9, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF, + 0xA5, 0x14, 0x12, 0xFF, 0xCA, 0x6F, 0x5A, 0xFF, 0xBF, 0x54, 0x39, 0xFF, 0xBA, 0x52, 0x37, 0xFF, + 0xB4, 0x4F, 0x36, 0xFF, 0xAF, 0x4D, 0x34, 0xFF, 0x88, 0x65, 0x56, 0xFF, 0x76, 0x5F, 0x5A, 0xFF, + 0x71, 0x5B, 0x56, 0xFF, 0x6B, 0x58, 0x53, 0xFF, 0x77, 0x60, 0x5B, 0xFF, 0x98, 0x0C, 0x0B, 0xF7, + 0x81, 0x81, 0x81, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xB2, 0xB2, 0xB2, 0xFF, 0xB9, 0xB9, 0xB9, 0xFF, + 0xA4, 0x02, 0x01, 0xFF, 0xC7, 0x69, 0x51, 0xFF, 0xB8, 0x51, 0x37, 0xFF, 0xB2, 0x4E, 0x36, 0xFF, + 0xAD, 0x4C, 0x34, 0xFF, 0xAE, 0x65, 0x3A, 0xFF, 0x95, 0x99, 0x5D, 0xFF, 0x1D, 0x84, 0xA0, 0xFF, + 0x17, 0x7F, 0x99, 0xFF, 0x3D, 0x91, 0xA5, 0xFF, 0x3B, 0x8E, 0xA0, 0xFF, 0xA2, 0x01, 0x01, 0xFF, + 0x81, 0x81, 0x81, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xB9, 0xB9, 0xB9, 0xFF, 0xC4, 0xC4, 0xC4, 0xFF, + 0x9F, 0x12, 0x12, 0xFF, 0xCA, 0x7E, 0x6D, 0xFF, 0xB8, 0x5F, 0x48, 0xFF, 0xAB, 0x4C, 0x33, 0xFF, + 0xA6, 0x49, 0x32, 0xFF, 0xB1, 0x8B, 0x44, 0xFF, 0xB8, 0xBC, 0x50, 0xFF, 0x35, 0x80, 0x86, 0xFF, + 0x50, 0x9C, 0xAD, 0xFF, 0x27, 0x83, 0x97, 0xFF, 0x49, 0x6E, 0x77, 0xFF, 0x92, 0x08, 0x08, 0xF7, + 0x81, 0x81, 0x81, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xBC, 0x78, 0x78, 0xFF, 0x9C, 0x1D, 0x1A, 0xFF, 0xBD, 0x7E, 0x6D, 0xFF, 0xBE, 0x7F, 0x70, 0xFF, + 0xBD, 0x83, 0x74, 0xFF, 0xCD, 0xC7, 0x87, 0xFF, 0xCB, 0xD0, 0x89, 0xFF, 0xB4, 0xB4, 0x8A, 0xFF, + 0x5C, 0x93, 0xA0, 0xFF, 0x44, 0x65, 0x6D, 0xFF, 0x7B, 0x16, 0x18, 0xFF, 0x66, 0x1D, 0x1D, 0xA1, + 0x69, 0x69, 0x69, 0xB4, 0x81, 0x81, 0x81, 0xFF, 0x81, 0x81, 0x81, 0xFF, 0x81, 0x81, 0x81, 0xFF, + 0x81, 0x81, 0x81, 0xFF, 0x93, 0x40, 0x40, 0xFF, 0x9E, 0x06, 0x05, 0xFF, 0x99, 0x46, 0x3D, 0xFF, + 0x9E, 0x62, 0x4D, 0xFF, 0xA6, 0xA1, 0x4C, 0xFF, 0x9F, 0x9B, 0x4A, 0xFF, 0x94, 0x88, 0x45, 0xFF, + 0x4B, 0x3C, 0x43, 0xFF, 0x9A, 0x05, 0x05, 0xFF, 0x77, 0x1F, 0x1F, 0xBA, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x35, 0x16, 0x16, 0x55, 0x7F, 0x17, 0x17, 0xD3, + 0x9C, 0x0B, 0x0B, 0xF9, 0xA3, 0x02, 0x01, 0xFF, 0xA2, 0x01, 0x01, 0xFF, 0x9C, 0x0B, 0x0B, 0xF9, + 0x88, 0x1E, 0x1E, 0xD3, 0x41, 0x22, 0x22, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +}; + +static const uint8_t dat3[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x30, 0x30, 0x30, 0x52, 0x91, 0x91, 0x91, 0xF2, 0x99, 0x99, 0x99, 0xFF, 0x9C, 0x9C, 0x9C, 0xFF, + 0x9E, 0x9E, 0x9E, 0xFF, 0x9C, 0x9C, 0x9C, 0xFF, 0x99, 0x99, 0x99, 0xFF, 0x96, 0x96, 0x96, 0xFF, + 0x93, 0x93, 0x93, 0xFF, 0x8F, 0x8F, 0x8F, 0xFF, 0x8C, 0x8C, 0x8C, 0xFF, 0x88, 0x88, 0x88, 0xFF, + 0x84, 0x84, 0x84, 0xFF, 0x81, 0x81, 0x81, 0xFF, 0x7D, 0x7D, 0x7D, 0xFF, 0x7A, 0x7A, 0x7A, 0xFF, + 0x76, 0x76, 0x76, 0xFF, 0x72, 0x72, 0x72, 0xFF, 0x6F, 0x6F, 0x6F, 0xFF, 0x6B, 0x6B, 0x6B, 0xFF, + 0x68, 0x68, 0x68, 0xFF, 0x64, 0x64, 0x64, 0xFF, 0x5F, 0x5F, 0x5F, 0xF2, 0x1E, 0x1E, 0x1E, 0x52, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x8D, 0x8D, 0x8D, 0xEF, 0xFD, 0xFD, 0xFD, 0xFF, 0xFD, 0xFD, 0xFD, 0xFF, 0xFE, 0xFE, 0xFE, 0xFF, + 0xFE, 0xFE, 0xFE, 0xFF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFD, 0xFD, 0xFD, 0xFF, 0xFD, 0xFD, 0xFD, 0xFF, + 0xFD, 0xFD, 0xFD, 0xFF, 0xFD, 0xFD, 0xFD, 0xFF, 0xFC, 0xFC, 0xFC, 0xFF, 0xFC, 0xFC, 0xFC, 0xFF, + 0xFC, 0xFC, 0xFC, 0xFF, 0xFB, 0xFB, 0xFB, 0xFF, 0xFB, 0xFB, 0xFB, 0xFF, 0xFB, 0xFB, 0xFB, 0xFF, + 0xFA, 0xFA, 0xFA, 0xFF, 0xFA, 0xFA, 0xFA, 0xFF, 0xFA, 0xFA, 0xFA, 0xFF, 0xF9, 0xF9, 0xF9, 0xFF, + 0xF9, 0xF9, 0xF9, 0xFF, 0xF9, 0xF9, 0xF9, 0xFF, 0xF8, 0xF8, 0xF8, 0xFF, 0x5D, 0x5D, 0x5D, 0xEF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x93, 0x93, 0x93, 0xFF, 0xFD, 0xFD, 0xFD, 0xFF, 0xDC, 0xDC, 0xDC, 0xFF, 0xDD, 0xDD, 0xDD, 0xFF, + 0xDE, 0xDE, 0xDE, 0xFF, 0xDE, 0xDE, 0xDE, 0xFF, 0xDF, 0xDF, 0xDF, 0xFF, 0xDF, 0xDF, 0xDF, 0xFF, + 0xE0, 0xE0, 0xE0, 0xFF, 0xE1, 0xE1, 0xE1, 0xFF, 0xE1, 0xE1, 0xE1, 0xFF, 0xE1, 0xE1, 0xE1, 0xFF, + 0xE2, 0xE2, 0xE2, 0xFF, 0xE2, 0xE2, 0xE2, 0xFF, 0xE2, 0xE2, 0xE2, 0xFF, 0xE2, 0xE2, 0xE2, 0xFF, + 0xE3, 0xE3, 0xE3, 0xFF, 0xE3, 0xE3, 0xE3, 0xFF, 0xE3, 0xE3, 0xE3, 0xFF, 0xE3, 0xE3, 0xE3, 0xFF, + 0xE3, 0xE3, 0xE3, 0xFF, 0xE2, 0xE2, 0xE2, 0xFF, 0xF8, 0xF8, 0xF8, 0xFF, 0x5D, 0x5D, 0x5D, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x92, 0x92, 0x92, 0xFF, 0xFE, 0xFE, 0xFE, 0xFF, 0xDD, 0xDD, 0xDD, 0xFF, 0x78, 0x78, 0x78, 0xFF, + 0x8D, 0x8D, 0x8D, 0xFF, 0x8E, 0x8E, 0x8E, 0xFF, 0x8F, 0x8F, 0x8F, 0xFF, 0x8F, 0x8F, 0x8F, 0xFF, + 0x78, 0x78, 0x78, 0xFF, 0x8F, 0x8F, 0x8F, 0xFF, 0x90, 0x90, 0x90, 0xFF, 0x90, 0x90, 0x90, 0xFF, + 0x7A, 0x7A, 0x7A, 0xFF, 0x91, 0x91, 0x91, 0xFF, 0x91, 0x91, 0x91, 0xFF, 0x91, 0x91, 0x91, 0xFF, + 0x7B, 0x7B, 0x7B, 0xFF, 0x91, 0x91, 0x91, 0xFF, 0x91, 0x91, 0x91, 0xFF, 0x91, 0x91, 0x91, 0xFF, + 0x7D, 0x7D, 0x7D, 0xFF, 0xE3, 0xE3, 0xE3, 0xFF, 0xF8, 0xF8, 0xF8, 0xFF, 0x5D, 0x5D, 0x5D, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x90, 0x90, 0x90, 0xFF, 0xFE, 0xFE, 0xFE, 0xFF, 0xDE, 0xDE, 0xDE, 0xFF, 0x94, 0x94, 0x94, 0xFF, + 0xB0, 0xB0, 0xB0, 0xFF, 0xB1, 0xB1, 0xB1, 0xFF, 0xB1, 0xB1, 0xB1, 0xFF, 0xB1, 0xB1, 0xB1, 0xFF, + 0x96, 0x96, 0x96, 0xFF, 0xB2, 0xB2, 0xB2, 0xFF, 0xB3, 0xB3, 0xB3, 0xFF, 0xB3, 0xB3, 0xB3, 0xFF, + 0x98, 0x98, 0x98, 0xFF, 0xB4, 0xB4, 0xB4, 0xFF, 0xB4, 0xB4, 0xB4, 0xFF, 0xB5, 0xB5, 0xB5, 0xFF, + 0x99, 0x99, 0x99, 0xFF, 0xB5, 0xB5, 0xB5, 0xFF, 0xB5, 0xB5, 0xB5, 0xFF, 0xB5, 0xB5, 0xB5, 0xFF, + 0x99, 0x99, 0x99, 0xFF, 0xE4, 0xE4, 0xE4, 0xFF, 0xF8, 0xF8, 0xF8, 0xFF, 0x5C, 0x5C, 0x5C, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x8E, 0x8E, 0x8E, 0xFF, 0xFD, 0xFD, 0xFD, 0xFF, 0xDF, 0xDF, 0xDF, 0xFF, 0x94, 0x94, 0x94, 0xFF, + 0xB1, 0xB1, 0xB1, 0xFF, 0xB1, 0xB1, 0xB1, 0xFF, 0xB2, 0xB2, 0xB2, 0xFF, 0xB2, 0xB2, 0xB2, 0xFF, + 0x97, 0x97, 0x97, 0xFF, 0xB3, 0xB3, 0xB3, 0xFF, 0xB4, 0xB4, 0xB4, 0xFF, 0xB4, 0xB4, 0xB4, 0xFF, + 0x99, 0x99, 0x99, 0xFF, 0xB5, 0xB5, 0xB5, 0xFF, 0xB5, 0xB5, 0xB5, 0xFF, 0xB5, 0xB5, 0xB5, 0xFF, + 0x99, 0x99, 0x99, 0xFF, 0xB5, 0xB5, 0xB5, 0xFF, 0xB5, 0xB5, 0xB5, 0xFF, 0xB5, 0xB5, 0xB5, 0xFF, + 0x99, 0x99, 0x99, 0xFF, 0xE5, 0xE5, 0xE5, 0xFF, 0xF8, 0xF8, 0xF8, 0xFF, 0x5C, 0x5C, 0x5C, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x8B, 0x8B, 0x8B, 0xFF, 0xFD, 0xFD, 0xFD, 0xFF, 0xDF, 0xDF, 0xDF, 0xFF, 0x7A, 0x7A, 0x7A, 0xFF, + 0x91, 0x91, 0x91, 0xFF, 0x92, 0x92, 0x92, 0xFF, 0x92, 0x92, 0x92, 0xFF, 0x93, 0x93, 0x93, 0xFF, + 0x7D, 0x7D, 0x7D, 0xFF, 0x94, 0x94, 0x94, 0xFF, 0x94, 0x94, 0x94, 0xFF, 0x94, 0x94, 0x94, 0xFF, + 0x7D, 0x7D, 0x7D, 0xFF, 0x94, 0x94, 0x94, 0xFF, 0x94, 0x94, 0x94, 0xFF, 0x95, 0x95, 0x95, 0xFF, + 0x7E, 0x7E, 0x7E, 0xFF, 0x95, 0x95, 0x95, 0xFF, 0x95, 0x95, 0x95, 0xFF, 0x95, 0x95, 0x95, 0xFF, + 0x7E, 0x7E, 0x7E, 0xFF, 0xE6, 0xE6, 0xE6, 0xFF, 0xF8, 0xF8, 0xF8, 0xFF, 0x5B, 0x5B, 0x5B, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x89, 0x89, 0x89, 0xFF, 0xFD, 0xFD, 0xFD, 0xFF, 0xE0, 0xE0, 0xE0, 0xFF, 0x94, 0x94, 0x94, 0xFF, + 0xB0, 0xB0, 0xB0, 0xFF, 0xB0, 0xB0, 0xB0, 0xFF, 0xB1, 0xB1, 0xB1, 0xFF, 0xB2, 0xB2, 0xB2, 0xFF, + 0x97, 0x97, 0x97, 0xFF, 0xE2, 0xE2, 0xE2, 0xFF, 0xE3, 0xE3, 0xE3, 0xFF, 0xE3, 0xE3, 0xE3, 0xFF, + 0xC0, 0xC0, 0xC0, 0xFF, 0xE4, 0xE4, 0xE4, 0xFF, 0xE4, 0xE4, 0xE4, 0xFF, 0xE5, 0xE5, 0xE5, 0xFF, + 0xC1, 0xC1, 0xC1, 0xFF, 0xE5, 0xE5, 0xE5, 0xFF, 0xE5, 0xE5, 0xE5, 0xFF, 0xE5, 0xE5, 0xE5, 0xFF, + 0xC1, 0xC1, 0xC1, 0xFF, 0xE8, 0xE8, 0xE8, 0xFF, 0xF8, 0xF8, 0xF8, 0xFF, 0x5A, 0x5A, 0x5A, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x86, 0x86, 0x86, 0xFF, 0xFD, 0xFD, 0xFD, 0xFF, 0xE1, 0xE1, 0xE1, 0xFF, 0x7B, 0x7B, 0x7B, 0xFF, + 0x92, 0x92, 0x92, 0xFF, 0x93, 0x93, 0x93, 0xFF, 0x94, 0x94, 0x94, 0xFF, 0x94, 0x94, 0x94, 0xFF, + 0x7D, 0x7D, 0x7D, 0xFF, 0xBD, 0xBD, 0xBD, 0xFF, 0xBD, 0xBD, 0xBD, 0xFF, 0xBD, 0xBD, 0xBD, 0xFF, + 0xA0, 0xA0, 0xA0, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF, 0xBF, 0xBF, 0xBF, 0xFF, + 0xA1, 0xA1, 0xA1, 0xFF, 0xBF, 0xBF, 0xBF, 0xFF, 0xBF, 0xBF, 0xBF, 0xFF, 0xBF, 0xBF, 0xBF, 0xFF, + 0xA1, 0xA1, 0xA1, 0xFF, 0xE9, 0xE9, 0xE9, 0xFF, 0xF8, 0xF8, 0xF8, 0xFF, 0x59, 0x59, 0x59, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x83, 0x83, 0x83, 0xFF, 0xFD, 0xFD, 0xFD, 0xFF, 0xE1, 0xE1, 0xE1, 0xFF, 0x94, 0x94, 0x94, 0xFF, + 0xB1, 0xB1, 0xB1, 0xFF, 0xB2, 0xB2, 0xB2, 0xFF, 0xB3, 0xB3, 0xB3, 0xFF, 0xB3, 0xB3, 0xB3, 0xFF, + 0x97, 0x97, 0x97, 0xFF, 0xE4, 0xE4, 0xE4, 0xFF, 0xE5, 0xE5, 0xE5, 0xFF, 0xE5, 0xE5, 0xE5, 0xFF, + 0xC2, 0xC2, 0xC2, 0xFF, 0xE6, 0xE6, 0xE6, 0xFF, 0xE6, 0xE6, 0xE6, 0xFF, 0xE7, 0xE7, 0xE7, 0xFF, + 0xC3, 0xC3, 0xC3, 0xFF, 0xE7, 0xE7, 0xE7, 0xFF, 0xE7, 0xE7, 0xE7, 0xFF, 0xE7, 0xE7, 0xE7, 0xFF, + 0xC3, 0xC3, 0xC3, 0xFF, 0xEA, 0xEA, 0xEA, 0xFF, 0xF8, 0xF8, 0xF8, 0xFF, 0x58, 0x58, 0x58, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x80, 0x80, 0x80, 0xFF, 0xFC, 0xFC, 0xFC, 0xFF, 0xE2, 0xE2, 0xE2, 0xFF, 0x7C, 0x7C, 0x7C, 0xFF, + 0x94, 0x94, 0x94, 0xFF, 0x94, 0x94, 0x94, 0xFF, 0x94, 0x94, 0x94, 0xFF, 0x94, 0x94, 0x94, 0xFF, + 0x7E, 0x7E, 0x7E, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF, 0xBE, 0xBE, 0xBE, 0xFF, 0xBF, 0xBF, 0xBF, 0xFF, + 0xA2, 0xA2, 0xA2, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xC1, 0xC1, 0xC1, 0xFF, + 0xA3, 0xA3, 0xA3, 0xFF, 0xC1, 0xC1, 0xC1, 0xFF, 0xC1, 0xC1, 0xC1, 0xFF, 0xC1, 0xC1, 0xC1, 0xFF, + 0xA3, 0xA3, 0xA3, 0xFF, 0xEB, 0xEB, 0xEB, 0xFF, 0xF8, 0xF8, 0xF8, 0xFF, 0x57, 0x57, 0x57, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x7D, 0x7D, 0x7D, 0xFF, 0xFC, 0xFC, 0xFC, 0xFF, 0xE3, 0xE3, 0xE3, 0xFF, 0x96, 0x96, 0x96, 0xFF, + 0xB3, 0xB3, 0xB3, 0xFF, 0xB3, 0xB3, 0xB3, 0xFF, 0xB3, 0xB3, 0xB3, 0xFF, 0xB4, 0xB4, 0xB4, 0xFF, + 0x99, 0x99, 0x99, 0xFF, 0xE6, 0xE6, 0xE6, 0xFF, 0xE6, 0xE6, 0xE6, 0xFF, 0xE7, 0xE7, 0xE7, 0xFF, + 0xC4, 0xC4, 0xC4, 0xFF, 0xE8, 0xE8, 0xE8, 0xFF, 0xE8, 0xE8, 0xE8, 0xFF, 0xE9, 0xE9, 0xE9, 0xFF, + 0xC4, 0xC4, 0xC4, 0xFF, 0xE9, 0xE9, 0xE9, 0xFF, 0xE9, 0xE9, 0xE9, 0xFF, 0xE9, 0xE9, 0xE9, 0xFF, + 0xC4, 0xC4, 0xC4, 0xFF, 0xEC, 0xEC, 0xEC, 0xFF, 0xF8, 0xF8, 0xF8, 0xFF, 0x55, 0x55, 0x55, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x7A, 0x7A, 0x7A, 0xFF, 0xFC, 0xFC, 0xFC, 0xFF, 0xE3, 0xE3, 0xE3, 0xFF, 0x7D, 0x7D, 0x7D, 0xFF, + 0x94, 0x94, 0x94, 0xFF, 0x94, 0x94, 0x94, 0xFF, 0x95, 0x95, 0x95, 0xFF, 0x96, 0x96, 0x96, 0xFF, + 0x7F, 0x7F, 0x7F, 0xFF, 0xBF, 0xBF, 0xBF, 0xFF, 0xC0, 0xC0, 0xC0, 0xFF, 0xC1, 0xC1, 0xC1, 0xFF, + 0xA3, 0xA3, 0xA3, 0xFF, 0xC1, 0xC1, 0xC1, 0xFF, 0xC1, 0xC1, 0xC1, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, + 0xA4, 0xA4, 0xA4, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, + 0xA4, 0xA4, 0xA4, 0xFF, 0xED, 0xED, 0xED, 0xFF, 0xF8, 0xF8, 0xF8, 0xFF, 0x54, 0x54, 0x54, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x77, 0x77, 0x77, 0xFF, 0xFB, 0xFB, 0xFB, 0xFF, 0xE4, 0xE4, 0xE4, 0xFF, 0x97, 0x97, 0x97, 0xFF, + 0xB3, 0xB3, 0xB3, 0xFF, 0xB4, 0xB4, 0xB4, 0xFF, 0xB5, 0xB5, 0xB5, 0xFF, 0xB6, 0xB6, 0xB6, 0xFF, + 0x99, 0x99, 0x99, 0xFF, 0xE7, 0xE7, 0xE7, 0xFF, 0xE8, 0xE8, 0xE8, 0xFF, 0xE9, 0xE9, 0xE9, 0xFF, + 0xC4, 0xC4, 0xC4, 0xFF, 0xEA, 0xEA, 0xEA, 0xFF, 0xEA, 0xEA, 0xEA, 0xFF, 0xEB, 0xEB, 0xEB, 0xFF, + 0xC6, 0xC6, 0xC6, 0xFF, 0xEB, 0xEB, 0xEB, 0xFF, 0xEB, 0xEB, 0xEB, 0xFF, 0xEB, 0xEB, 0xEB, 0xFF, + 0xC6, 0xC6, 0xC6, 0xFF, 0xEE, 0xEE, 0xEE, 0xFF, 0xF8, 0xF8, 0xF8, 0xFF, 0x52, 0x52, 0x52, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x73, 0x73, 0x73, 0xFF, 0xFB, 0xFB, 0xFB, 0xFF, 0xE4, 0xE4, 0xE4, 0xFF, 0x7D, 0x7D, 0x7D, 0xFF, + 0x94, 0x94, 0x94, 0xFF, 0x95, 0x95, 0x95, 0xFF, 0x96, 0x96, 0x96, 0xFF, 0x97, 0x97, 0x97, 0xFF, + 0x7F, 0x7F, 0x7F, 0xFF, 0xC1, 0xC1, 0xC1, 0xFF, 0xC1, 0xC1, 0xC1, 0xFF, 0xC2, 0xC2, 0xC2, 0xFF, + 0xA3, 0xA2, 0xA2, 0xFF, 0xAB, 0x91, 0x91, 0xFF, 0x94, 0x60, 0x60, 0xFF, 0x84, 0x3D, 0x3D, 0xFF, + 0x78, 0x25, 0x25, 0xFF, 0x80, 0x27, 0x27, 0xFF, 0x7E, 0x2B, 0x2B, 0xFF, 0x84, 0x3D, 0x3D, 0xFF, + 0x86, 0x52, 0x52, 0xFF, 0xCC, 0xB2, 0xB2, 0xFF, 0xF6, 0xF5, 0xF5, 0xFF, 0x50, 0x50, 0x50, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x70, 0x70, 0x70, 0xFF, 0xFB, 0xFB, 0xFB, 0xFF, 0xE5, 0xE5, 0xE5, 0xFF, 0x97, 0x97, 0x97, 0xFF, + 0xB4, 0xB4, 0xB4, 0xFF, 0xB5, 0xB5, 0xB5, 0xFF, 0xB6, 0xB6, 0xB6, 0xFF, 0xB6, 0xB6, 0xB6, 0xFF, + 0x9A, 0x9A, 0x9A, 0xFF, 0xE9, 0xE9, 0xE9, 0xFF, 0xE6, 0xE4, 0xE4, 0xFF, 0xB1, 0x85, 0x85, 0xFF, + 0x7A, 0x1B, 0x1B, 0xFF, 0xA6, 0x2F, 0x2F, 0xFF, 0xD3, 0x50, 0x50, 0xFF, 0xF2, 0x67, 0x67, 0xFF, + 0xFF, 0x70, 0x70, 0xFF, 0xFE, 0x6E, 0x6E, 0xFF, 0xFC, 0x69, 0x69, 0xFF, 0xED, 0x5B, 0x5B, 0xFF, + 0xCD, 0x43, 0x43, 0xFF, 0xA2, 0x25, 0x25, 0xFF, 0x7E, 0x1D, 0x1D, 0xFF, 0x58, 0x2C, 0x2C, 0xFF, + 0x02, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x6D, 0x6D, 0x6D, 0xFF, 0xFB, 0xFB, 0xFB, 0xFF, 0xE5, 0xE5, 0xE5, 0xFF, 0x7D, 0x7D, 0x7D, 0xFF, + 0x95, 0x95, 0x95, 0xFF, 0x96, 0x96, 0x96, 0xFF, 0x97, 0x97, 0x97, 0xFF, 0x97, 0x97, 0x97, 0xFF, + 0x80, 0x80, 0x80, 0xFF, 0xB7, 0xAB, 0xAB, 0xFF, 0x7B, 0x28, 0x28, 0xFF, 0xAC, 0x34, 0x34, 0xFF, + 0xF5, 0x6A, 0x6A, 0xFF, 0xFF, 0x70, 0x70, 0xFF, 0xFF, 0x70, 0x70, 0xFF, 0xFE, 0x6F, 0x6F, 0xFF, + 0xFC, 0x6A, 0x6A, 0xFF, 0xFA, 0x65, 0x65, 0xFF, 0xF8, 0x60, 0x60, 0xFF, 0xF5, 0x5C, 0x5C, 0xFF, + 0xF3, 0x57, 0x57, 0xFF, 0xF1, 0x52, 0x52, 0xFF, 0xE6, 0x48, 0x48, 0xFF, 0xA1, 0x1F, 0x1F, 0xFF, + 0x53, 0x00, 0x00, 0xCB, 0x0C, 0x00, 0x00, 0x1D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x6A, 0x6A, 0x6A, 0xFF, 0xFA, 0xFA, 0xFA, 0xFF, 0xE6, 0xE6, 0xE6, 0xFF, 0x98, 0x98, 0x98, 0xFF, + 0xB5, 0xB5, 0xB5, 0xFF, 0xB6, 0xB6, 0xB6, 0xFF, 0xB6, 0xB6, 0xB6, 0xFF, 0xB7, 0xB7, 0xB7, 0xFF, + 0x98, 0x92, 0x92, 0xFF, 0x7E, 0x26, 0x26, 0xFF, 0xCB, 0x50, 0x50, 0xFF, 0xFF, 0x74, 0x74, 0xFF, + 0xFF, 0x70, 0x70, 0xFF, 0xFF, 0x70, 0x70, 0xFF, 0xFD, 0x6B, 0x6B, 0xFF, 0xFA, 0x67, 0x67, 0xFF, + 0xF8, 0x62, 0x62, 0xFF, 0xF6, 0x5D, 0x5D, 0xFF, 0xF4, 0x58, 0x58, 0xFF, 0xF1, 0x53, 0x53, 0xFF, + 0xEF, 0x4E, 0x4E, 0xFF, 0xED, 0x49, 0x49, 0xFF, 0xEB, 0x44, 0x44, 0xFF, 0xE9, 0x3F, 0x3F, 0xFF, + 0xB6, 0x24, 0x24, 0xFF, 0x57, 0x00, 0x00, 0xD7, 0x06, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x66, 0x66, 0x66, 0xFF, 0xFA, 0xFA, 0xFA, 0xFF, 0xE6, 0xE6, 0xE6, 0xFF, 0x7E, 0x7E, 0x7E, 0xFF, + 0x96, 0x96, 0x96, 0xFF, 0x97, 0x97, 0x97, 0xFF, 0x97, 0x97, 0x97, 0xFF, 0x98, 0x98, 0x98, 0xFF, + 0x73, 0x3D, 0x3D, 0xFF, 0xA6, 0x37, 0x37, 0xFF, 0xFF, 0x79, 0x79, 0xFF, 0xFF, 0x72, 0x72, 0xFF, + 0xFD, 0x6D, 0x6D, 0xFF, 0xFB, 0x68, 0x68, 0xFF, 0xF9, 0x63, 0x63, 0xFF, 0xF6, 0x5E, 0x5E, 0xFF, + 0xF4, 0x59, 0x59, 0xFF, 0xF2, 0x54, 0x54, 0xFF, 0xF0, 0x4F, 0x4F, 0xFF, 0xEE, 0x4A, 0x4A, 0xFF, + 0xEB, 0x45, 0x45, 0xFF, 0xE9, 0x41, 0x41, 0xFF, 0xE7, 0x3C, 0x3C, 0xFF, 0xE5, 0x37, 0x37, 0xFF, + 0xE2, 0x35, 0x35, 0xFF, 0x91, 0x13, 0x13, 0xFF, 0x36, 0x00, 0x00, 0x86, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x63, 0x63, 0x63, 0xFF, 0xFA, 0xFA, 0xFA, 0xFF, 0xE6, 0xE6, 0xE6, 0xFF, 0x98, 0x98, 0x98, 0xFF, + 0xB5, 0xB5, 0xB5, 0xFF, 0xB6, 0xB6, 0xB6, 0xFF, 0xB7, 0xB7, 0xB7, 0xFF, 0xB8, 0xB8, 0xB8, 0xFF, + 0x6E, 0x15, 0x15, 0xFF, 0xDF, 0x6D, 0x6D, 0xFF, 0xFE, 0x75, 0x75, 0xFF, 0xFB, 0x69, 0x69, 0xFF, + 0xF9, 0x64, 0x64, 0xFF, 0xF7, 0x5F, 0x5F, 0xFF, 0xF5, 0x5A, 0x5A, 0xFF, 0xF3, 0x55, 0x55, 0xFF, + 0xF0, 0x50, 0x50, 0xFF, 0xEE, 0x4C, 0x4C, 0xFF, 0xEC, 0x47, 0x47, 0xFF, 0xEA, 0x42, 0x42, 0xFF, + 0xE7, 0x3D, 0x3D, 0xFF, 0xE5, 0x38, 0x38, 0xFF, 0xE3, 0x33, 0x33, 0xFF, 0xE1, 0x2E, 0x2E, 0xFF, + 0xDF, 0x2D, 0x2D, 0xFF, 0xC2, 0x28, 0x28, 0xFF, 0x59, 0x00, 0x00, 0xDE, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x60, 0x60, 0x60, 0xFF, 0xF9, 0xF9, 0xF9, 0xFF, 0xE6, 0xE6, 0xE6, 0xFF, 0x7E, 0x7E, 0x7E, 0xFF, + 0x97, 0x97, 0x97, 0xFF, 0x97, 0x97, 0x97, 0xFF, 0x98, 0x98, 0x98, 0xFF, 0x98, 0x98, 0x98, 0xFF, + 0x67, 0x01, 0x01, 0xFF, 0xED, 0x7B, 0x7B, 0xFF, 0xFA, 0x6A, 0x6A, 0xFF, 0xF8, 0x60, 0x60, 0xFF, + 0xF5, 0x5B, 0x5B, 0xFF, 0xF3, 0x56, 0x56, 0xFF, 0xF1, 0x52, 0x52, 0xFF, 0xEF, 0x4D, 0x4D, 0xFF, + 0xEC, 0x48, 0x48, 0xFF, 0xCD, 0x84, 0x78, 0xFF, 0x77, 0x7C, 0xAE, 0xFF, 0x77, 0x7B, 0xAD, 0xFF, + 0x72, 0x75, 0xA7, 0xFF, 0x6B, 0x6F, 0xA1, 0xFF, 0x67, 0x69, 0x9B, 0xFF, 0x60, 0x63, 0x96, 0xFF, + 0x5E, 0x60, 0x91, 0xFF, 0x7E, 0x5E, 0x82, 0xFF, 0x66, 0x00, 0x00, 0xFC, 0x00, 0x00, 0x00, 0x02, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x5D, 0x5D, 0x5D, 0xFF, 0xF9, 0xF9, 0xF9, 0xFF, 0xE6, 0xE6, 0xE6, 0xFF, 0x99, 0x99, 0x99, 0xFF, + 0xB6, 0xB6, 0xB6, 0xFF, 0xB6, 0xB6, 0xB6, 0xFF, 0xB7, 0xB7, 0xB7, 0xFF, 0xB8, 0xB8, 0xB8, 0xFF, + 0x67, 0x00, 0x00, 0xFF, 0xD8, 0x62, 0x62, 0xFF, 0xF7, 0x6D, 0x6D, 0xFF, 0xF4, 0x58, 0x58, 0xFF, + 0xF1, 0x53, 0x53, 0xFF, 0xEF, 0x4E, 0x4E, 0xFF, 0xED, 0x49, 0x49, 0xFF, 0xEB, 0x44, 0x44, 0xFF, + 0xE8, 0x43, 0x41, 0xFF, 0xC5, 0xE1, 0x8C, 0xFF, 0x8A, 0x93, 0x9F, 0xFF, 0x58, 0x89, 0xC7, 0xFF, + 0x51, 0x82, 0xC1, 0xFF, 0x4B, 0x7C, 0xBA, 0xFF, 0x44, 0x75, 0xB4, 0xFF, 0x3D, 0x6E, 0xAE, 0xFF, + 0x45, 0x72, 0xAD, 0xFF, 0x6A, 0x60, 0x87, 0xFF, 0x67, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x0E, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x59, 0x59, 0x59, 0xFF, 0xF9, 0xF9, 0xF9, 0xFF, 0xE7, 0xE7, 0xE7, 0xFF, 0x7E, 0x7E, 0x7E, 0xFF, + 0x97, 0x97, 0x97, 0xFF, 0x97, 0x97, 0x97, 0xFF, 0x98, 0x98, 0x98, 0xFF, 0x98, 0x98, 0x98, 0xFF, + 0x69, 0x0D, 0x0D, 0xFF, 0xA3, 0x24, 0x24, 0xFF, 0xEF, 0x7B, 0x7B, 0xFF, 0xF1, 0x5A, 0x5A, 0xFF, + 0xEE, 0x4A, 0x4A, 0xFF, 0xEB, 0x45, 0x45, 0xFF, 0xE9, 0x40, 0x40, 0xFF, 0xE7, 0x3C, 0x3C, 0xFF, + 0xD8, 0x6B, 0x4D, 0xFF, 0xAD, 0xE7, 0x73, 0xFF, 0xAB, 0xC3, 0x5F, 0xFF, 0x55, 0x85, 0xC0, 0xFF, + 0x4D, 0x7E, 0xBD, 0xFF, 0x47, 0x78, 0xB7, 0xFF, 0x40, 0x71, 0xB0, 0xFF, 0x43, 0x72, 0xAE, 0xFF, + 0x6B, 0x7A, 0xA6, 0xFF, 0x54, 0x42, 0x67, 0xFF, 0x5C, 0x00, 0x00, 0xE8, 0x00, 0x00, 0x00, 0x16, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x56, 0x56, 0x56, 0xFF, 0xF8, 0xF8, 0xF8, 0xFF, 0xE7, 0xE7, 0xE7, 0xFF, 0x99, 0x99, 0x99, 0xFF, + 0xB6, 0xB6, 0xB6, 0xFF, 0xB6, 0xB6, 0xB6, 0xFF, 0xB7, 0xB7, 0xB7, 0xFF, 0xB8, 0xB8, 0xB8, 0xFF, + 0x77, 0x39, 0x39, 0xFF, 0x7A, 0x09, 0x09, 0xFF, 0xBB, 0x32, 0x32, 0xFF, 0xE8, 0x71, 0x71, 0xFF, + 0xED, 0x61, 0x61, 0xFF, 0xE8, 0x42, 0x42, 0xFF, 0xE5, 0x38, 0x38, 0xFF, 0xE3, 0x33, 0x33, 0xFF, + 0xBA, 0x9F, 0x4E, 0xFF, 0x99, 0xE0, 0x53, 0xFF, 0x8F, 0xDC, 0x43, 0xFF, 0x84, 0x8A, 0x66, 0xFF, + 0x49, 0x7A, 0xB9, 0xFF, 0x47, 0x77, 0xB4, 0xFF, 0x58, 0x82, 0xB9, 0xFF, 0x79, 0x7F, 0xA6, 0xFF, + 0x45, 0x5E, 0x90, 0xFF, 0x65, 0x17, 0x23, 0xFF, 0x3E, 0x00, 0x00, 0xAC, 0x00, 0x00, 0x00, 0x13, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x53, 0x53, 0x53, 0xFF, 0xF8, 0xF8, 0xF8, 0xFF, 0xE6, 0xE6, 0xE6, 0xFF, 0x7E, 0x7E, 0x7E, 0xFF, + 0x97, 0x97, 0x97, 0xFF, 0x97, 0x97, 0x97, 0xFF, 0x98, 0x98, 0x98, 0xFF, 0x98, 0x98, 0x98, 0xFF, + 0x76, 0x6B, 0x6B, 0xFF, 0x6D, 0x0E, 0x0E, 0xFF, 0x88, 0x11, 0x11, 0xFF, 0xB0, 0x23, 0x23, 0xFF, + 0xCA, 0x45, 0x45, 0xFF, 0xE2, 0x66, 0x66, 0xFF, 0xE8, 0x5D, 0x5D, 0xFF, 0xE2, 0x4F, 0x4B, 0xFF, + 0xA1, 0xD6, 0x56, 0xFF, 0x91, 0xDC, 0x47, 0xFF, 0x8B, 0xD9, 0x3C, 0xFF, 0x90, 0xC9, 0x3A, 0xFF, + 0x74, 0x94, 0xBB, 0xFF, 0x84, 0x8E, 0xB4, 0xFF, 0x70, 0x68, 0x8E, 0xFF, 0x3B, 0x5E, 0x92, 0xFF, + 0x60, 0x29, 0x42, 0xFF, 0x5F, 0x00, 0x00, 0xEF, 0x0B, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x08, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x4F, 0x4F, 0x4F, 0xFF, 0xF8, 0xF8, 0xF8, 0xFF, 0xE6, 0xE6, 0xE6, 0xFF, 0xE5, 0xE5, 0xE5, 0xFF, + 0xE6, 0xE6, 0xE6, 0xFF, 0xE7, 0xE7, 0xE7, 0xFF, 0xE8, 0xE8, 0xE8, 0xFF, 0xE9, 0xE9, 0xE9, 0xFF, + 0xE6, 0xE6, 0xE6, 0xFF, 0xBD, 0xA9, 0xA9, 0xFF, 0x71, 0x15, 0x15, 0xFF, 0x7B, 0x0C, 0x0C, 0xFF, + 0xA2, 0x1D, 0x1D, 0xFF, 0xAD, 0x1B, 0x1B, 0xFF, 0xB6, 0x27, 0x27, 0xFF, 0xB2, 0x4F, 0x33, 0xFF, + 0x93, 0xA6, 0x40, 0xFF, 0x96, 0xA8, 0x40, 0xFF, 0x91, 0xA7, 0x3C, 0xFF, 0x86, 0x9F, 0x33, 0xFF, + 0x6E, 0x67, 0x5B, 0xFF, 0x37, 0x5C, 0x93, 0xFF, 0x54, 0x4D, 0x75, 0xFF, 0x6B, 0x18, 0x23, 0xFF, + 0x5C, 0x00, 0x00, 0xEB, 0x13, 0x00, 0x00, 0x59, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0D, + 0x4C, 0x4C, 0x4C, 0xF1, 0xF7, 0xF7, 0xF7, 0xFF, 0xF6, 0xF6, 0xF6, 0xFF, 0xF6, 0xF6, 0xF6, 0xFF, + 0xF6, 0xF6, 0xF6, 0xFF, 0xF7, 0xF7, 0xF7, 0xFF, 0xF7, 0xF7, 0xF7, 0xFF, 0xF7, 0xF7, 0xF7, 0xFF, + 0xF7, 0xF7, 0xF7, 0xFF, 0xF0, 0xF0, 0xF0, 0xFF, 0xD1, 0xC9, 0xC9, 0xFF, 0x90, 0x53, 0x53, 0xFF, + 0x6A, 0x05, 0x05, 0xFF, 0x77, 0x0A, 0x0A, 0xFF, 0x8E, 0x14, 0x14, 0xFF, 0x91, 0x33, 0x1C, 0xFF, + 0x72, 0x87, 0x23, 0xFF, 0x70, 0x90, 0x24, 0xFF, 0x6E, 0x8F, 0x23, 0xFF, 0x73, 0x7C, 0x1F, 0xFF, + 0x70, 0x3C, 0x31, 0xFF, 0x6C, 0x14, 0x1B, 0xFF, 0x6A, 0x05, 0x05, 0xFF, 0x53, 0x16, 0x16, 0xFB, + 0x08, 0x00, 0x00, 0x52, 0x00, 0x00, 0x00, 0x1D, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0D, 0x00, 0x00, 0x00, 0x22, + 0x19, 0x19, 0x19, 0x78, 0x53, 0x53, 0x53, 0xF6, 0x56, 0x56, 0x56, 0xFF, 0x56, 0x56, 0x56, 0xFF, + 0x56, 0x56, 0x56, 0xFF, 0x56, 0x56, 0x56, 0xFF, 0x56, 0x56, 0x56, 0xFF, 0x56, 0x56, 0x56, 0xFF, + 0x56, 0x56, 0x56, 0xFF, 0x56, 0x56, 0x56, 0xFF, 0x55, 0x55, 0x55, 0xFF, 0x4F, 0x4F, 0x4F, 0xFF, + 0x4B, 0x43, 0x43, 0xFF, 0x52, 0x28, 0x28, 0xFF, 0x5A, 0x16, 0x16, 0xFF, 0x61, 0x0A, 0x0A, 0xFF, + 0x65, 0x04, 0x04, 0xFF, 0x67, 0x00, 0x00, 0xFF, 0x65, 0x04, 0x04, 0xFF, 0x60, 0x09, 0x09, 0xFF, + 0x59, 0x15, 0x15, 0xFF, 0x50, 0x26, 0x26, 0xFF, 0x45, 0x3C, 0x3C, 0xF9, 0x15, 0x15, 0x15, 0x93, + 0x00, 0x00, 0x00, 0x3A, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x1D, + 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x47, 0x00, 0x00, 0x00, 0x4A, + 0x00, 0x00, 0x00, 0x4A, 0x00, 0x00, 0x00, 0x4A, 0x00, 0x00, 0x00, 0x4A, 0x00, 0x00, 0x00, 0x4A, + 0x00, 0x00, 0x00, 0x4A, 0x00, 0x00, 0x00, 0x4A, 0x00, 0x00, 0x00, 0x4A, 0x00, 0x00, 0x00, 0x4A, + 0x00, 0x00, 0x00, 0x4C, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0x00, 0x5E, 0x00, 0x00, 0x00, 0x65, + 0x00, 0x00, 0x00, 0x69, 0x00, 0x00, 0x00, 0x6B, 0x00, 0x00, 0x00, 0x6B, 0x00, 0x00, 0x00, 0x69, + 0x00, 0x00, 0x00, 0x63, 0x00, 0x00, 0x00, 0x52, 0x00, 0x00, 0x00, 0x4B, 0x00, 0x00, 0x00, 0x3B, + 0x00, 0x00, 0x00, 0x29, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x16, + 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x16, + 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x16, + 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x16, + 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x17, + 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x08, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +}; + +static const struct { + const char *name; + void *data; + int width; + int height; + int stride; +} files[] = { + { "andlabs_16x16test_24june2016.png", dat0, 16, 16, 64 }, + { "andlabs_32x32test_24june2016.png", dat1, 32, 32, 128 }, + { "tango-icon-theme-0.8.90_16x16_x-office-spreadsheet.png", dat2, 16, 16, 64 }, + { "tango-icon-theme-0.8.90_32x32_x-office-spreadsheet.png", dat3, 32, 32, 128 }, +}; + +void appendImageNamed(uiImage *img, const char *name) +{ + int i; + + i = 0; + for (;;) { + if (strcmp(name, files[i].name) == 0) { + uiImageAppend(img, files[i].data, files[i].width, files[i].height, files[i].stride); + return; + } + i++; + } +} + diff --git a/dep/libui/test/images/andlabs_16x16test_24june2016.png b/dep/libui/test/images/andlabs_16x16test_24june2016.png new file mode 100644 index 0000000..a4c27d9 Binary files /dev/null and b/dep/libui/test/images/andlabs_16x16test_24june2016.png differ diff --git a/dep/libui/test/images/andlabs_32x32test_24june2016.png b/dep/libui/test/images/andlabs_32x32test_24june2016.png new file mode 100644 index 0000000..e1c33fc Binary files /dev/null and b/dep/libui/test/images/andlabs_32x32test_24june2016.png differ diff --git a/dep/libui/test/images/gen.go b/dep/libui/test/images/gen.go new file mode 100644 index 0000000..7ded83e --- /dev/null +++ b/dep/libui/test/images/gen.go @@ -0,0 +1,94 @@ +// 25 june 2016 +package main + +import ( + "fmt" + "os" + "image" + "image/draw" + _ "image/png" +) + +type img struct { + filename string + data []byte + width int + height int + stride int +} + +func main() { + if len(os.Args[1:]) == 0 { + panic("no files specified") + } + + images := make([]*img, 0, len(os.Args[1:])) + for _, fn := range os.Args[1:] { + f, err := os.Open(fn) + if err != nil { + panic(err) + } + ii, _, err := image.Decode(f) + if err != nil { + panic(err) + } + f.Close() + + i := image.NewRGBA(ii.Bounds()) + draw.Draw(i, i.Rect, ii, ii.Bounds().Min, draw.Src) + + im := &img{ + filename: fn, + data: i.Pix, + width: i.Rect.Dx(), + height: i.Rect.Dy(), + stride: i.Stride, + } + images = append(images, im) + } + + fmt.Println("// auto-generated by images/gen.go") + fmt.Println("#include \"test.h\"") + fmt.Println() + for i, im := range images { + fmt.Printf("static const uint8_t dat%d[] = {", i) + for j := 0; j < len(im.data); j++ { + if (j % 16) == 0 { + fmt.Printf("\n\t") + } else { + fmt.Printf(" ") + } + fmt.Printf("0x%02X,", im.data[j]) + + } + fmt.Println("\n};") + fmt.Println() + } + fmt.Println("static const struct {") + fmt.Println(" const char *name;") + fmt.Println(" void *data;") + fmt.Println(" int width;") + fmt.Println(" int height;") + fmt.Println(" int stride;") + fmt.Println("} files[] = {") + for i, im := range images { + fmt.Printf(" { %q, dat%d, %d, %d, %d },\n", + im.filename, i, im.width, im.height, im.stride) + } + fmt.Println("};") + fmt.Println() + fmt.Println("void appendImageNamed(uiImage *img, const char *name)") + fmt.Println("{") + fmt.Println(" int i;") + fmt.Println("") + fmt.Println(" i = 0;") + fmt.Println(" for (;;) {") + fmt.Println(" if (strcmp(name, files[i].name) == 0) {") + fmt.Println(" uiImageAppend(img, files[i].data, files[i].width, files[i].height, files[i].stride);") + fmt.Println(" return;") + fmt.Println(" }") + fmt.Println(" i++;") + fmt.Println(" }") + fmt.Println("}") + fmt.Println() +} diff --git a/dep/libui/test/images/tango-icon-theme-0.8.90_16x16_x-office-spreadsheet.png b/dep/libui/test/images/tango-icon-theme-0.8.90_16x16_x-office-spreadsheet.png new file mode 100644 index 0000000..a6b1268 Binary files /dev/null and b/dep/libui/test/images/tango-icon-theme-0.8.90_16x16_x-office-spreadsheet.png differ diff --git a/dep/libui/test/images/tango-icon-theme-0.8.90_32x32_x-office-spreadsheet.png b/dep/libui/test/images/tango-icon-theme-0.8.90_32x32_x-office-spreadsheet.png new file mode 100644 index 0000000..c0ccb7a Binary files /dev/null and b/dep/libui/test/images/tango-icon-theme-0.8.90_32x32_x-office-spreadsheet.png differ diff --git a/dep/libui/test/main.c b/dep/libui/test/main.c new file mode 100644 index 0000000..2f66826 --- /dev/null +++ b/dep/libui/test/main.c @@ -0,0 +1,181 @@ +// 22 april 2015 +#include "test.h" + +// TODOs +// - blank page affects menus negatively on Windows + +void die(const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + fprintf(stderr, "[test program] "); + vfprintf(stderr, fmt, ap); + fprintf(stderr, "\n"); + va_end(ap); + abort(); +} + +int onClosing(uiWindow *w, void *data) +{ + printf("in onClosing()\n"); + uiQuit(); + return 1; +} + +int onShouldQuit(void *data) +{ + printf("in onShouldQuit()\n"); + if (uiMenuItemChecked(shouldQuitItem)) { + uiControlDestroy(uiControl(data)); + return 1; + } + return 0; +} + +uiBox *mainBox; +uiTab *mainTab; + +uiBox *(*newhbox)(void); +uiBox *(*newvbox)(void); + +int main(int argc, char *argv[]) +{ + uiInitOptions o; + int i; + const char *err; + uiWindow *w; + uiBox *page2, *page3, *page4, *page5; + uiBox *page6, *page7, *page8, *page9, *page10; + uiBox *page11, *page12, *page13; + uiTab *page14; + uiBox *page15; + uiBox *page16; + uiTab *outerTab; + uiTab *innerTab; + int nomenus = 0; + int startspaced = 0; + int steps = 0; + + newhbox = uiNewHorizontalBox; + newvbox = uiNewVerticalBox; + + memset(&o, 0, sizeof (uiInitOptions)); + for (i = 1; i < argc; i++) + if (strcmp(argv[i], "nomenus") == 0) + nomenus = 1; + else if (strcmp(argv[i], "startspaced") == 0) + startspaced = 1; + else if (strcmp(argv[i], "swaphv") == 0) { + newhbox = uiNewVerticalBox; + newvbox = uiNewHorizontalBox; + } else if (strcmp(argv[i], "steps") == 0) + steps = 1; + else { + fprintf(stderr, "%s: unrecognized option %s\n", argv[0], argv[i]); + return 1; + } + + err = uiInit(&o); + if (err != NULL) { + fprintf(stderr, "error initializing ui: %s\n", err); + uiFreeInitError(err); + return 1; + } + + if (!nomenus) + initMenus(); + + w = newWindow("Main Window", 320, 240, 1); + uiWindowOnClosing(w, onClosing, NULL); + printf("main window %p\n", (void *) w); + + uiOnShouldQuit(onShouldQuit, w); + + mainBox = newHorizontalBox(); + uiWindowSetChild(w, uiControl(mainBox)); + + outerTab = newTab(); + uiBoxAppend(mainBox, uiControl(outerTab), 1); + + mainTab = newTab(); + uiTabAppend(outerTab, "Pages 1-5", uiControl(mainTab)); + + // page 1 uses page 2's uiGroup + page2 = makePage2(); + + makePage1(w); + uiTabAppend(mainTab, "Page 1", uiControl(page1)); + + uiTabAppend(mainTab, "Page 2", uiControl(page2)); + + uiTabAppend(mainTab, "Empty Page", uiControl(uiNewHorizontalBox())); + + page3 = makePage3(); + uiTabAppend(mainTab, "Page 3", uiControl(page3)); + + page4 = makePage4(); + uiTabAppend(mainTab, "Page 4", uiControl(page4)); + + page5 = makePage5(w); + uiTabAppend(mainTab, "Page 5", uiControl(page5)); + + innerTab = newTab(); + uiTabAppend(outerTab, "Pages 6-10", uiControl(innerTab)); + + page6 = makePage6(); + uiTabAppend(innerTab, "Page 6", uiControl(page6)); + + page7 = makePage7(); + uiTabAppend(innerTab, "Page 7", uiControl(page7)); + +/* page8 = makePage8(); + uiTabAppend(innerTab, "Page 8", uiControl(page8)); + + page9 = makePage9(); + uiTabAppend(innerTab, "Page 9", uiControl(page9)); + + page10 = makePage10(); + uiTabAppend(innerTab, "Page 10", uiControl(page10)); +*/ + innerTab = newTab(); + uiTabAppend(outerTab, "Pages 11-15", uiControl(innerTab)); + +// page11 = makePage11(); +// uiTabAppend(innerTab, "Page 11", uiControl(page11)); + + page12 = makePage12(); + uiTabAppend(innerTab, "Page 12", uiControl(page12)); + + page13 = makePage13(); + uiTabAppend(innerTab, "Page 13", uiControl(page13)); + + page14 = makePage14(); + uiTabAppend(innerTab, "Page 14", uiControl(page14)); + + page15 = makePage15(w); + uiTabAppend(innerTab, "Page 15", uiControl(page15)); + + innerTab = newTab(); + uiTabAppend(outerTab, "Pages 16-?", uiControl(innerTab)); + + page16 = makePage16(); + uiTabAppend(innerTab, "Page 16", uiControl(page16)); + + if (startspaced) + setSpaced(1); + + uiControlShow(uiControl(w)); + if (!steps) + uiMain(); + else { + uiMainSteps(); + while (uiMainStep(1)) + ; + } + printf("after uiMain()\n"); + freePage16(); + uiUninit(); + printf("after uiUninit()\n"); + return 0; +} diff --git a/dep/libui/test/menus.c b/dep/libui/test/menus.c new file mode 100644 index 0000000..87ff80a --- /dev/null +++ b/dep/libui/test/menus.c @@ -0,0 +1,112 @@ +// 23 april 2015 +#include "test.h" + +uiMenu *fileMenu; +uiMenuItem *newItem; +uiMenuItem *openItem; +uiMenuItem *shouldQuitItem; +uiMenuItem *quitItem; +uiMenu *editMenu; +uiMenuItem *undoItem; +uiMenuItem *checkItem; +uiMenuItem *accelItem; +uiMenuItem *prefsItem; +uiMenu *testMenu; +uiMenuItem *enabledItem; +uiMenuItem *enableThisItem; +uiMenuItem *forceCheckedItem; +uiMenuItem *forceUncheckedItem; +uiMenuItem *whatWindowItem; +uiMenu *moreTestsMenu; +uiMenuItem *quitEnabledItem; +uiMenuItem *prefsEnabledItem; +uiMenuItem *aboutEnabledItem; +uiMenuItem *checkEnabledItem; +uiMenu *multiMenu; +uiMenu *helpMenu; +uiMenuItem *helpItem; +uiMenuItem *aboutItem; + +static void enableItemTest(uiMenuItem *item, uiWindow *w, void *data) +{ + if (uiMenuItemChecked(item)) + uiMenuItemEnable(uiMenuItem(data)); + else + uiMenuItemDisable(uiMenuItem(data)); +} + +static void forceOn(uiMenuItem *item, uiWindow *w, void *data) +{ + uiMenuItemSetChecked(enabledItem, 1); +} + +static void forceOff(uiMenuItem *item, uiWindow *w, void *data) +{ + uiMenuItemSetChecked(enabledItem, 0); +} + +static void whatWindow(uiMenuItem *item, uiWindow *w, void *data) +{ + printf("menu item clicked on window %p\n", (void *) w); +} + +void initMenus(void) +{ + fileMenu = uiNewMenu("File"); + newItem = uiMenuAppendItem(fileMenu, "New"); + openItem = uiMenuAppendItem(fileMenu, "Open"); + uiMenuAppendSeparator(fileMenu); + shouldQuitItem = uiMenuAppendCheckItem(fileMenu, "Should Quit"); + quitItem = uiMenuAppendQuitItem(fileMenu); + + editMenu = uiNewMenu("Edit"); + undoItem = uiMenuAppendItem(editMenu, "Undo"); + uiMenuItemDisable(undoItem); + uiMenuAppendSeparator(editMenu); + checkItem = uiMenuAppendCheckItem(editMenu, "Check Me\tTest"); + accelItem = uiMenuAppendItem(editMenu, "A&ccele&&rator T_es__t"); + prefsItem = uiMenuAppendPreferencesItem(editMenu); + + testMenu = uiNewMenu("Test"); + enabledItem = uiMenuAppendCheckItem(testMenu, "Enable Below Item"); + uiMenuItemSetChecked(enabledItem, 1); + enableThisItem = uiMenuAppendItem(testMenu, "This Will Be Enabled"); + uiMenuItemOnClicked(enabledItem, enableItemTest, enableThisItem); + forceCheckedItem = uiMenuAppendItem(testMenu, "Force Above Checked"); + uiMenuItemOnClicked(forceCheckedItem, forceOn, NULL); + forceUncheckedItem = uiMenuAppendItem(testMenu, "Force Above Unchecked"); + uiMenuItemOnClicked(forceUncheckedItem, forceOff, NULL); + uiMenuAppendSeparator(testMenu); + whatWindowItem = uiMenuAppendItem(testMenu, "What Window?"); + uiMenuItemOnClicked(whatWindowItem, whatWindow, NULL); + + moreTestsMenu = uiNewMenu("More Tests"); + quitEnabledItem = uiMenuAppendCheckItem(moreTestsMenu, "Quit Item Enabled"); + uiMenuItemSetChecked(quitEnabledItem, 1); + prefsEnabledItem = uiMenuAppendCheckItem(moreTestsMenu, "Preferences Item Enabled"); + uiMenuItemSetChecked(prefsEnabledItem, 1); + aboutEnabledItem = uiMenuAppendCheckItem(moreTestsMenu, "About Item Enabled"); + uiMenuItemSetChecked(aboutEnabledItem, 1); + uiMenuAppendSeparator(moreTestsMenu); + checkEnabledItem = uiMenuAppendCheckItem(moreTestsMenu, "Check Me Item Enabled"); + uiMenuItemSetChecked(checkEnabledItem, 1); + + multiMenu = uiNewMenu("Multi"); + uiMenuAppendSeparator(multiMenu); + uiMenuAppendSeparator(multiMenu); + uiMenuAppendItem(multiMenu, "Item && Item && Item"); + uiMenuAppendSeparator(multiMenu); + uiMenuAppendSeparator(multiMenu); + uiMenuAppendItem(multiMenu, "Item __ Item __ Item"); + uiMenuAppendSeparator(multiMenu); + uiMenuAppendSeparator(multiMenu); + + helpMenu = uiNewMenu("Help"); + helpItem = uiMenuAppendItem(helpMenu, "Help"); + aboutItem = uiMenuAppendAboutItem(helpMenu); + + uiMenuItemOnClicked(quitEnabledItem, enableItemTest, quitItem); + uiMenuItemOnClicked(prefsEnabledItem, enableItemTest, prefsItem); + uiMenuItemOnClicked(aboutEnabledItem, enableItemTest, aboutItem); + uiMenuItemOnClicked(checkEnabledItem, enableItemTest, checkItem); +} diff --git a/dep/libui/test/meson.build b/dep/libui/test/meson.build new file mode 100644 index 0000000..a1296ac --- /dev/null +++ b/dep/libui/test/meson.build @@ -0,0 +1,48 @@ +# 23 march 2019 + +libui_test_sources = [ + 'drawtests.c', + 'images.c', + 'main.c', + 'menus.c', + 'page1.c', + 'page2.c', + 'page3.c', + 'page4.c', + 'page5.c', + 'page6.c', + 'page7.c', + 'page7a.c', + 'page7b.c', + 'page7c.c', +# 'page8.c', +# 'page9.c', +# 'page10.c', + 'page11.c', + 'page12.c', + 'page13.c', + 'page14.c', + 'page15.c', + 'page16.c', + 'spaced.c', +] + +if libui_OS == 'windows' + libui_test_manifest = 'test.manifest' + if libui_mode == 'static' + libui_test_manifest = 'test.static.manifest' + endif + libui_test_sources += [ + windows.compile_resources('resources.rc', + args: libui_manifest_args, + depend_files: [libui_test_manifest]), + ] +endif + +# TODO meson doesn't let us name this target test, but also doesn't seem to provide a way to override the executable name???? we'll probably need to file a feature request for this +# TODO once we upgrade to 0.49.0, add pie: true +executable('tester', libui_test_sources, + dependencies: libui_binary_deps, + link_with: libui_libui, + gui_app: false, + install: false) diff --git a/dep/libui/test/page1.c b/dep/libui/test/page1.c new file mode 100644 index 0000000..2115ba2 --- /dev/null +++ b/dep/libui/test/page1.c @@ -0,0 +1,171 @@ +// 29 april 2015 +#include "test.h" + +static uiEntry *entry; +static uiCheckbox *spaced; + +#define TEXT(name, type, getter, setter) \ + static void get ## name ## Text(uiButton *b, void *data) \ + { \ + char *text; \ + text = getter(type(data)); \ + uiEntrySetText(entry, text); \ + uiFreeText(text); \ + } \ + static void set ## name ## Text(uiButton *b, void *data) \ + { \ + char *text; \ + text = uiEntryText(entry); \ + setter(type(data), text); \ + uiFreeText(text); \ + } +TEXT(Window, uiWindow, uiWindowTitle, uiWindowSetTitle) +TEXT(Button, uiButton, uiButtonText, uiButtonSetText) +TEXT(Checkbox, uiCheckbox, uiCheckboxText, uiCheckboxSetText) +TEXT(Label, uiLabel, uiLabelText, uiLabelSetText) +TEXT(Group, uiGroup, uiGroupTitle, uiGroupSetTitle) + +static void onChanged(uiEntry *e, void *data) +{ + printf("onChanged()\n"); +} + +static void toggleSpaced(uiCheckbox *c, void *data) +{ + setSpaced(uiCheckboxChecked(spaced)); +} + +static void forceSpaced(uiButton *b, void *data) +{ + uiCheckboxSetChecked(spaced, data != NULL); +} + +static void showSpaced(uiButton *b, void *data) +{ + char s[12]; + + querySpaced(s); + uiEntrySetText(entry, s); +} + +#define SHED(method, Method) \ + static void method ## Control(uiButton *b, void *data) \ + { \ + uiControl ## Method(uiControl(data)); \ + } +SHED(show, Show) +SHED(hide, Hide) +SHED(enable, Enable) +SHED(disable, Disable) + +uiBox *page1; + +void makePage1(uiWindow *w) +{ + uiButton *getButton, *setButton; + uiBox *hbox; + uiBox *testBox; + uiLabel *label; + + page1 = newVerticalBox(); + + entry = uiNewEntry(); + uiEntryOnChanged(entry, onChanged, NULL); + uiBoxAppend(page1, uiControl(entry), 0); + + spaced = uiNewCheckbox("Spaced"); + uiCheckboxOnToggled(spaced, toggleSpaced, NULL); + label = uiNewLabel("Label"); + + hbox = newHorizontalBox(); + getButton = uiNewButton("Get Window Text"); + uiButtonOnClicked(getButton, getWindowText, w); + setButton = uiNewButton("Set Window Text"); + uiButtonOnClicked(setButton, setWindowText, w); + uiBoxAppend(hbox, uiControl(getButton), 1); + uiBoxAppend(hbox, uiControl(setButton), 1); + uiBoxAppend(page1, uiControl(hbox), 0); + + hbox = newHorizontalBox(); + getButton = uiNewButton("Get Button Text"); + uiButtonOnClicked(getButton, getButtonText, getButton); + setButton = uiNewButton("Set Button Text"); + uiButtonOnClicked(setButton, setButtonText, getButton); + uiBoxAppend(hbox, uiControl(getButton), 1); + uiBoxAppend(hbox, uiControl(setButton), 1); + uiBoxAppend(page1, uiControl(hbox), 0); + + hbox = newHorizontalBox(); + getButton = uiNewButton("Get Checkbox Text"); + uiButtonOnClicked(getButton, getCheckboxText, spaced); + setButton = uiNewButton("Set Checkbox Text"); + uiButtonOnClicked(setButton, setCheckboxText, spaced); + uiBoxAppend(hbox, uiControl(getButton), 1); + uiBoxAppend(hbox, uiControl(setButton), 1); + uiBoxAppend(page1, uiControl(hbox), 0); + + hbox = newHorizontalBox(); + getButton = uiNewButton("Get Label Text"); + uiButtonOnClicked(getButton, getLabelText, label); + setButton = uiNewButton("Set Label Text"); + uiButtonOnClicked(setButton, setLabelText, label); + uiBoxAppend(hbox, uiControl(getButton), 1); + uiBoxAppend(hbox, uiControl(setButton), 1); + uiBoxAppend(page1, uiControl(hbox), 0); + + hbox = newHorizontalBox(); + getButton = uiNewButton("Get Group Text"); + uiButtonOnClicked(getButton, getGroupText, page2group); + setButton = uiNewButton("Set Group Text"); + uiButtonOnClicked(setButton, setGroupText, page2group); + uiBoxAppend(hbox, uiControl(getButton), 1); + uiBoxAppend(hbox, uiControl(setButton), 1); + uiBoxAppend(page1, uiControl(hbox), 0); + + hbox = newHorizontalBox(); + uiBoxAppend(hbox, uiControl(spaced), 1); + getButton = uiNewButton("On"); + uiButtonOnClicked(getButton, forceSpaced, getButton); + uiBoxAppend(hbox, uiControl(getButton), 0); + getButton = uiNewButton("Off"); + uiButtonOnClicked(getButton, forceSpaced, NULL); + uiBoxAppend(hbox, uiControl(getButton), 0); + getButton = uiNewButton("Show"); + uiButtonOnClicked(getButton, showSpaced, NULL); + uiBoxAppend(hbox, uiControl(getButton), 0); + uiBoxAppend(page1, uiControl(hbox), 0); + + testBox = newHorizontalBox(); + setButton = uiNewButton("Button"); + uiBoxAppend(testBox, uiControl(setButton), 1); + getButton = uiNewButton("Show"); + uiButtonOnClicked(getButton, showControl, setButton); + uiBoxAppend(testBox, uiControl(getButton), 0); + getButton = uiNewButton("Hide"); + uiButtonOnClicked(getButton, hideControl, setButton); + uiBoxAppend(testBox, uiControl(getButton), 0); + getButton = uiNewButton("Enable"); + uiButtonOnClicked(getButton, enableControl, setButton); + uiBoxAppend(testBox, uiControl(getButton), 0); + getButton = uiNewButton("Disable"); + uiButtonOnClicked(getButton, disableControl, setButton); + uiBoxAppend(testBox, uiControl(getButton), 0); + uiBoxAppend(page1, uiControl(testBox), 0); + + hbox = newHorizontalBox(); + getButton = uiNewButton("Show Box"); + uiButtonOnClicked(getButton, showControl, testBox); + uiBoxAppend(hbox, uiControl(getButton), 1); + getButton = uiNewButton("Hide Box"); + uiButtonOnClicked(getButton, hideControl, testBox); + uiBoxAppend(hbox, uiControl(getButton), 1); + getButton = uiNewButton("Enable Box"); + uiButtonOnClicked(getButton, enableControl, testBox); + uiBoxAppend(hbox, uiControl(getButton), 1); + getButton = uiNewButton("Disable Box"); + uiButtonOnClicked(getButton, disableControl, testBox); + uiBoxAppend(hbox, uiControl(getButton), 1); + uiBoxAppend(page1, uiControl(hbox), 0); + + uiBoxAppend(page1, uiControl(label), 0); +} diff --git a/dep/libui/test/page10.c b/dep/libui/test/page10.c new file mode 100644 index 0000000..d7f26a7 --- /dev/null +++ b/dep/libui/test/page10.c @@ -0,0 +1,185 @@ +// 22 december 2015 +#include "test.h" + +static uiEntry *textString; +static uiFontButton *textFontButton; +static uiColorButton *textColorButton; +static uiEntry *textWidth; +static uiButton *textApply; +static uiCheckbox *noZ; +static uiArea *textArea; +static uiAreaHandler textAreaHandler; + +static double entryDouble(uiEntry *e) +{ + char *s; + double d; + + s = uiEntryText(e); + d = atof(s); + uiFreeText(s); + return d; +} + +static void handlerDraw(uiAreaHandler *a, uiArea *area, uiAreaDrawParams *dp) +{ + uiDrawTextFont *font; + uiDrawTextLayout *layout; + double r, g, b, al; + char surrogates[1 + 4 + 1 + 1]; + char composed[2 + 2 + 2 + 3 + 2 + 1]; + double width, height; + + font = uiFontButtonFont(textFontButton); + + layout = uiDrawNewTextLayout("One two three four", font, -1); + uiDrawTextLayoutSetColor(layout, + 4, 7, + 1, 0, 0, 1); + uiDrawTextLayoutSetColor(layout, + 8, 14, + 1, 0, 0.5, 0.5); + uiColorButtonColor(textColorButton, &r, &g, &b, &al); + uiDrawTextLayoutSetColor(layout, + 14, 18, + r, g, b, al); + uiDrawText(dp->Context, 10, 10, layout); + uiDrawTextLayoutExtents(layout, &width, &height); + uiDrawFreeTextLayout(layout); + + surrogates[0] = 'x'; + surrogates[1] = 0xF0; // surrogates D800 DF08 + surrogates[2] = 0x90; + surrogates[3] = 0x8C; + surrogates[4] = 0x88; + surrogates[5] = 'y'; + surrogates[6] = '\0'; + + layout = uiDrawNewTextLayout(surrogates, font, -1); + uiDrawTextLayoutSetColor(layout, + 1, 2, + 1, 0, 0.5, 0.5); + uiDrawText(dp->Context, 10, 10 + height, layout); + uiDrawFreeTextLayout(layout); + + composed[0] = 'z'; + composed[1] = 'z'; + composed[2] = 0xC3; // 2 + composed[3] = 0xA9; + composed[4] = 'z'; + composed[5] = 'z'; + composed[6] = 0x65; // 5 + composed[7] = 0xCC; + composed[8] = 0x81; + composed[9] = 'z'; + composed[10] = 'z'; + composed[11] = '\0'; + + layout = uiDrawNewTextLayout(composed, font, -1); + uiDrawTextLayoutSetColor(layout, + 2, 3, + 1, 0, 0.5, 0.5); + uiDrawTextLayoutSetColor(layout, + 5, 6, + 1, 0, 0.5, 0.5); + if (!uiCheckboxChecked(noZ)) + uiDrawTextLayoutSetColor(layout, + 6, 7, + 0.5, 0, 1, 0.5); + uiDrawText(dp->Context, 10, 10 + height + height, layout); + uiDrawFreeTextLayout(layout); + + uiDrawFreeTextFont(font); +} + +static void handlerMouseEvent(uiAreaHandler *a, uiArea *area, uiAreaMouseEvent *e) +{ + // do nothing +} + +static void handlerMouseCrossed(uiAreaHandler *ah, uiArea *a, int left) +{ + // do nothing +} + +static void handlerDragBroken(uiAreaHandler *ah, uiArea *a) +{ + // do nothing +} + +static int handlerKeyEvent(uiAreaHandler *ah, uiArea *a, uiAreaKeyEvent *e) +{ + // do nothing + return 0; +} + +static void onFontChanged(uiFontButton *b, void *data) +{ + uiAreaQueueRedrawAll(textArea); +} + +static void onColorChanged(uiColorButton *b, void *data) +{ + uiAreaQueueRedrawAll(textArea); +} + +static void onNoZ(uiCheckbox *b, void *data) +{ + uiAreaQueueRedrawAll(textArea); +} + +uiBox *makePage10(void) +{ + uiBox *page10; + uiBox *vbox; + uiBox *hbox; + + page10 = newVerticalBox(); + vbox = page10; + + hbox = newHorizontalBox(); + uiBoxAppend(vbox, uiControl(hbox), 0); + + textString = uiNewEntry(); + // TODO make it placeholder + uiEntrySetText(textString, "Enter text here"); + uiBoxAppend(hbox, uiControl(textString), 1); + + textFontButton = uiNewFontButton(); + uiFontButtonOnChanged(textFontButton, onFontChanged, NULL); + uiBoxAppend(hbox, uiControl(textFontButton), 1); + + textColorButton = uiNewColorButton(); + uiColorButtonOnChanged(textColorButton, onColorChanged, NULL); + uiBoxAppend(hbox, uiControl(textColorButton), 1); + + hbox = newHorizontalBox(); + uiBoxAppend(vbox, uiControl(hbox), 0); + + textApply = uiNewButton("Apply"); + uiBoxAppend(hbox, uiControl(textApply), 1); + + textWidth = uiNewEntry(); + uiEntrySetText(textWidth, "-1"); + uiBoxAppend(hbox, uiControl(textWidth), 1); + + noZ = uiNewCheckbox("No Z Color"); + uiCheckboxOnToggled(noZ, onNoZ, NULL); + uiBoxAppend(hbox, uiControl(noZ), 0); + + textAreaHandler.Draw = handlerDraw; + textAreaHandler.MouseEvent = handlerMouseEvent; + textAreaHandler.MouseCrossed = handlerMouseCrossed; + textAreaHandler.DragBroken = handlerDragBroken; + textAreaHandler.KeyEvent = handlerKeyEvent; + textArea = uiNewArea(&textAreaHandler); + uiBoxAppend(vbox, uiControl(textArea), 1); + + // dummy objects to test single-activation + hbox = newHorizontalBox(); + uiBoxAppend(vbox, uiControl(hbox), 0); + uiBoxAppend(hbox, uiControl(uiNewFontButton()), 1); + uiBoxAppend(hbox, uiControl(uiNewColorButton()), 1); + + return page10; +} diff --git a/dep/libui/test/page11.c b/dep/libui/test/page11.c new file mode 100644 index 0000000..02ad213 --- /dev/null +++ b/dep/libui/test/page11.c @@ -0,0 +1,54 @@ +// 14 may 2016 +#include "test.h" + +// TODO add a test for childless windows +// TODO add tests for contianers with all controls hidden + +static uiGroup *newg(const char *n, int s) +{ + uiGroup *g; + + g = uiNewGroup(n); + if (s) + uiGroupSetChild(g, NULL); + return g; +} + +static uiTab *newt(int tt) +{ + uiTab *t; + + t = uiNewTab(); + if (tt) + uiTabAppend(t, "Test", NULL); + return t; +} + +uiBox *makePage11(void) +{ + uiBox *page11; + uiBox *ns; + uiBox *s; + + page11 = newHorizontalBox(); + + ns = newVerticalBox(); + uiBoxAppend(ns, uiControl(newg("", 0)), 0); + uiBoxAppend(ns, uiControl(newg("", 1)), 0); + uiBoxAppend(ns, uiControl(newg("Group", 0)), 0); + uiBoxAppend(ns, uiControl(newg("Group", 1)), 0); + uiBoxAppend(ns, uiControl(newt(0)), 0); + uiBoxAppend(ns, uiControl(newt(1)), 0); + uiBoxAppend(page11, uiControl(ns), 1); + + s = newVerticalBox(); + uiBoxAppend(s, uiControl(newg("", 0)), 1); + uiBoxAppend(s, uiControl(newg("", 1)), 1); + uiBoxAppend(s, uiControl(newg("Group", 0)), 1); + uiBoxAppend(s, uiControl(newg("Group", 1)), 1); + uiBoxAppend(s, uiControl(newt(0)), 1); + uiBoxAppend(s, uiControl(newt(1)), 1); + uiBoxAppend(page11, uiControl(s), 1); + + return page11; +} diff --git a/dep/libui/test/page12.c b/dep/libui/test/page12.c new file mode 100644 index 0000000..5a8e963 --- /dev/null +++ b/dep/libui/test/page12.c @@ -0,0 +1,60 @@ +// 22 may 2016 +#include "test.h" + +// TODO OS X: if the hboxes are empty, the text views don't show up + +static void meChanged(uiMultilineEntry *e, void *data) +{ + printf("%s changed\n", (char *) data); +} + +static void setClicked(uiButton *b, void *data) +{ + uiMultilineEntrySetText(uiMultilineEntry(data), "set"); +} + +static void appendClicked(uiButton *b, void *data) +{ + uiMultilineEntryAppend(uiMultilineEntry(data), "append\n"); +} + +static uiBox *half(uiMultilineEntry *(*mk)(void), const char *which) +{ + uiBox *vbox, *hbox; + uiMultilineEntry *me; + uiButton *button; + + vbox = newVerticalBox(); + + me = (*mk)(); + uiMultilineEntryOnChanged(me, meChanged, (void *) which); + uiBoxAppend(vbox, uiControl(me), 1); + + hbox = newHorizontalBox(); + uiBoxAppend(vbox, uiControl(hbox), 0); + + button = uiNewButton("Set"); + uiButtonOnClicked(button, setClicked, me); + uiBoxAppend(hbox, uiControl(button), 0); + + button = uiNewButton("Append"); + uiButtonOnClicked(button, appendClicked, me); + uiBoxAppend(hbox, uiControl(button), 0); + + return vbox; +} + +uiBox *makePage12(void) +{ + uiBox *page12; + uiBox *b; + + page12 = newHorizontalBox(); + + b = half(uiNewMultilineEntry, "wrap"); + uiBoxAppend(page12, uiControl(b), 1); + b = half(uiNewNonWrappingMultilineEntry, "no wrap"); + uiBoxAppend(page12, uiControl(b), 1); + + return page12; +} diff --git a/dep/libui/test/page13.c b/dep/libui/test/page13.c new file mode 100644 index 0000000..5e6fd52 --- /dev/null +++ b/dep/libui/test/page13.c @@ -0,0 +1,157 @@ +// 28 may 2016 +#include "test.h" + +static int winClose(uiWindow *w, void *data) +{ + return 1; +} + +static void openTestWindow(uiBox *(*mkf)(void)) +{ + uiWindow *w; + uiBox *b; + uiCombobox *c; + uiEditableCombobox *e; + uiRadioButtons *r; + + w = uiNewWindow("Test", 100, 100, 0); + uiWindowOnClosing(w, winClose, NULL); + uiWindowSetMargined(w, 1); + b = (*mkf)(); + uiWindowSetChild(w, uiControl(b)); + +#define BA(x) uiBoxAppend(b, uiControl(x), 0) + BA(uiNewButton("")); + BA(uiNewCheckbox("")); + BA(uiNewEntry()); + BA(uiNewLabel("")); + BA(uiNewSpinbox(0, 100)); + BA(uiNewProgressBar()); + BA(uiNewSlider(0, 100)); + BA(uiNewHorizontalSeparator()); + c = uiNewCombobox(); + uiComboboxAppend(c, ""); + BA(c); + e = uiNewEditableCombobox(); + uiEditableComboboxAppend(e, ""); + BA(e); + r = uiNewRadioButtons(); + uiRadioButtonsAppend(r, ""); + BA(r); + BA(uiNewDateTimePicker()); + BA(uiNewDatePicker()); + BA(uiNewTimePicker()); + BA(uiNewMultilineEntry()); + // TODO nonscrolling and scrolling areas? + BA(uiNewFontButton()); + BA(uiNewColorButton()); + BA(uiNewPasswordEntry()); + BA(uiNewSearchEntry()); + BA(uiNewVerticalSeparator()); + + uiControlShow(uiControl(w)); +} + +static void buttonClicked(uiButton *b, void *data) +{ + openTestWindow((uiBox *(*)(void)) data); +} + +static void entryChanged(uiEntry *e, void *data) +{ + char *text; + + text = uiEntryText(e); + printf("%s entry changed: %s\n", (const char *) data, text); + uiFreeText(text); +} + +static void showHide(uiButton *b, void *data) +{ + uiControl *c = uiControl(data); + + if (uiControlVisible(c)) + uiControlHide(c); + else + uiControlShow(c); +} + +static void setIndeterminate(uiButton *b, void *data) +{ + uiProgressBar *p = uiProgressBar(data); + int value; + + value = uiProgressBarValue(p); + if (value == -1) + value = 50; + else + value = -1; + uiProgressBarSetValue(p, value); +} + +static void deleteFirst(uiButton *b, void *data) +{ + uiForm *f = uiForm(data); + + uiFormDelete(f, 0); +} + +uiBox *makePage13(void) +{ + uiBox *page13; + uiRadioButtons *rb; + uiButton *b; + uiForm *f; + uiEntry *e; + uiProgressBar *p; + + page13 = newVerticalBox(); + + rb = uiNewRadioButtons(); + uiRadioButtonsAppend(rb, "Item 1"); + uiRadioButtonsAppend(rb, "Item 2"); + uiRadioButtonsAppend(rb, "Item 3"); + uiBoxAppend(page13, uiControl(rb), 0); + + rb = uiNewRadioButtons(); + uiRadioButtonsAppend(rb, "Item A"); + uiRadioButtonsAppend(rb, "Item B"); + uiBoxAppend(page13, uiControl(rb), 0); + + b = uiNewButton("Horizontal"); + uiButtonOnClicked(b, buttonClicked, uiNewHorizontalBox); + uiBoxAppend(page13, uiControl(b), 0); + + b = uiNewButton("Vertical"); + uiButtonOnClicked(b, buttonClicked, uiNewVerticalBox); + uiBoxAppend(page13, uiControl(b), 0); + + f = newForm(); + + e = uiNewPasswordEntry(); + uiEntryOnChanged(e, entryChanged, "password"); + uiFormAppend(f, "Password Entry", uiControl(e), 0); + + e = uiNewSearchEntry(); + uiEntryOnChanged(e, entryChanged, "search"); + uiFormAppend(f, "Search Box", uiControl(e), 0); + + uiFormAppend(f, "MLE", uiControl(uiNewMultilineEntry()), 1); + + p = uiNewProgressBar(); + uiProgressBarSetValue(p, 50); + uiBoxAppend(page13, uiControl(p), 0); + b = uiNewButton("Toggle Indeterminate"); + uiButtonOnClicked(b, setIndeterminate, p); + uiBoxAppend(page13, uiControl(b), 0); + + b = uiNewButton("Show/Hide"); + uiButtonOnClicked(b, showHide, e); + uiBoxAppend(page13, uiControl(b), 0); + b = uiNewButton("Delete First"); + uiButtonOnClicked(b, deleteFirst, f); + uiBoxAppend(page13, uiControl(b), 0); + uiBoxAppend(page13, uiControl(f), 1); + + return page13; +} diff --git a/dep/libui/test/page14.c b/dep/libui/test/page14.c new file mode 100644 index 0000000..880534c --- /dev/null +++ b/dep/libui/test/page14.c @@ -0,0 +1,350 @@ +// 9 june 2016 +#include "test.h" + +// TODOs: +// - GTK+ - make all expanding controls the same size, to match the other OSs? will they match the other OSs? + +enum { + red, + green, + blue, + yellow, + white, + magenta, + orange, + purple, + cyan, +}; + +static const struct { + double r; + double g; + double b; +} colors[] = { + { 1, 0, 0 }, + { 0, 0.5, 0 }, + { 0, 0, 1 }, + { 1, 1, 0 }, + { 1, 1, 1 }, + { 1, 0, 1 }, + { 1, 0.65, 0 }, + { 0.5, 0, 0.5 }, + { 0, 1, 1 }, +}; + +static uiControl *testControl(const char *label, int color) +{ + uiColorButton *b; + + b = uiNewColorButton(); + uiColorButtonSetColor(b, colors[color].r, colors[color].g, colors[color].b, 1.0); + return uiControl(b); +} + +static uiControl *simpleGrid(void) +{ + uiGrid *g; + uiControl *t4; + + g = newGrid(); + uiGridAppend(g, testControl("1", red), + 0, 0, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + uiGridAppend(g, testControl("2", green), + 1, 0, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + uiGridAppend(g, testControl("3", blue), + 2, 0, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + t4 = testControl("4", green); + uiGridAppend(g, t4, + 0, 1, 1, 1, + 0, uiAlignFill, 1, uiAlignFill); + uiGridInsertAt(g, testControl("5", blue), + t4, uiAtTrailing, 2, 1, + 0, uiAlignFill, 0, uiAlignFill); + uiGridAppend(g, testControl("6", yellow), + -1, 0, 1, 2, + 1, uiAlignFill, 0, uiAlignFill); + return uiControl(g); +} + +static uiControl *boxComparison(void) +{ + uiBox *vbox; + uiGrid *g; + uiBox *hbox; + + vbox = newVerticalBox(); + uiBoxAppend(vbox, uiControl(uiNewLabel("Above")), 0); + uiBoxAppend(vbox, uiControl(uiNewHorizontalSeparator()), 0); + + hbox = newHorizontalBox(); + uiBoxAppend(vbox, uiControl(hbox), 0); + uiBoxAppend(hbox, testControl("1", white), 0); + uiBoxAppend(hbox, uiControl(uiNewLabel("A label")), 1); + uiBoxAppend(hbox, testControl("2", green), 0); + uiBoxAppend(hbox, uiControl(uiNewLabel("Another label")), 1); + uiBoxAppend(hbox, testControl("3", red), 0); + + uiBoxAppend(vbox, uiControl(uiNewHorizontalSeparator()), 0); + + g = newGrid(); + uiBoxAppend(vbox, uiControl(g), 0); + uiGridAppend(g, testControl("1", white), + 0, 0, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + uiGridAppend(g, uiControl(uiNewLabel("A label")), + 1, 0, 1, 1, + 1, uiAlignFill, 0, uiAlignFill); + uiGridAppend(g, testControl("2", green), + 2, 0, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + uiGridAppend(g, uiControl(uiNewLabel("Another label")), + 3, 0, 1, 1, + 1, uiAlignFill, 0, uiAlignFill); + uiGridAppend(g, testControl("3", red), + 4, 0, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + + uiBoxAppend(vbox, uiControl(uiNewHorizontalSeparator()), 0); + uiBoxAppend(vbox, uiControl(uiNewLabel("Below")), 0); + return uiControl(vbox); +} + +static uiControl *emptyLine(void) +{ + uiGrid *g; + + g = newGrid(); + uiGridAppend(g, testControl("(0, 0)", red), + 0, 0, 1, 1, + 1, uiAlignFill, 1, uiAlignFill); + uiGridAppend(g, testControl("(0, 1)", blue), + 0, 1, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + uiGridAppend(g, testControl("(10, 0)", green), + 10, 0, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + uiGridAppend(g, testControl("(10, 1)", magenta), + 10, 1, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + return uiControl(g); +} + +static uiControl *emptyGrid(void) +{ + uiGrid *g; + uiControl *t; + + g = newGrid(); + t = testControl("(0, 0)", red); + uiGridAppend(g, t, + 0, 0, 1, 1, + 1, uiAlignFill, 1, uiAlignFill); + uiControlHide(t); + return uiControl(g); +} + +// TODO insert (need specialized insert/delete) + +static uiControl *spanningGrid(void) +{ + uiGrid *g; + + g = newGrid(); + uiGridAppend(g, testControl("0", blue), + 0, 4, 4, 1, + 1, uiAlignFill, 0, uiAlignFill); + uiGridAppend(g, testControl("1", green), + 4, 0, 1, 4, + 0, uiAlignFill, 1, uiAlignFill); + uiGridAppend(g, testControl("2", red), + 3, 3, 1, 1, + 1, uiAlignFill, 1, uiAlignFill); + uiGridAppend(g, testControl("3", yellow), + 0, 3, 2, 1, + 0, uiAlignFill, 0, uiAlignFill); + uiGridAppend(g, testControl("4", orange), + 3, 0, 1, 2, + 0, uiAlignFill, 0, uiAlignFill); + uiGridAppend(g, testControl("5", purple), + 1, 1, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + uiGridAppend(g, testControl("6", white), + 0, 1, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + uiGridAppend(g, testControl("7", cyan), + 1, 0, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + return uiControl(g); +} + +// TODO make non-global +static uiButton *hideOne, *one, *showOne; + +static void onHideOne(uiButton *b, void *data) +{ + uiControlHide(uiControl(one)); +} + +static void onShowOne(uiButton *b, void *data) +{ + uiControlShow(uiControl(one)); +} + +static void onHideAll(uiButton *b, void *data) +{ + uiControlHide(uiControl(hideOne)); + uiControlHide(uiControl(one)); + uiControlHide(uiControl(showOne)); +} + +static void onShowAll(uiButton *b, void *data) +{ + uiControlShow(uiControl(hideOne)); + uiControlShow(uiControl(one)); + uiControlShow(uiControl(showOne)); +} + +#define AT(x) static void onInsert ## x(uiButton *b, void *data) \ + { \ + uiGrid *g = uiGrid(data); \ + uiGridInsertAt(g, uiControl(uiNewButton("Button")), \ + uiControl(b), uiAt ## x, 1, 1, \ + 0, uiAlignFill, 0, uiAlignFill); \ + } +AT(Leading) +AT(Top) +AT(Trailing) +AT(Bottom) + +static uiControl *assorted(void) +{ + uiGrid *outergrid; + uiGrid *innergrid; + uiButton *b; + + outergrid = newGrid(); + + innergrid = newGrid(); + one = uiNewButton("Test"); + uiGridAppend(innergrid, uiControl(one), + 1, 1, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + hideOne = uiNewButton("Hide One"); + uiButtonOnClicked(hideOne, onHideOne, NULL); + uiGridAppend(innergrid, uiControl(hideOne), + 0, 1, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + showOne = uiNewButton("Show One"); + uiButtonOnClicked(showOne, onShowOne, NULL); + uiGridAppend(innergrid, uiControl(showOne), + 2, 1, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + b = uiNewButton("Hide All"); + uiButtonOnClicked(b, onHideAll, NULL); + uiGridAppend(innergrid, uiControl(b), + 1, 0, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + b = uiNewButton("Show All"); + uiButtonOnClicked(b, onShowAll, NULL); + uiGridAppend(innergrid, uiControl(b), + 1, 2, 1, 1, + 0, uiAlignFill, 0, uiAlignFill); + uiGridAppend(outergrid, uiControl(innergrid), + 0, 0, 1, 1, + 1, uiAlignFill, 1, uiAlignFill); + + innergrid = newGrid(); + b = uiNewButton("Insert Trailing"); + uiButtonOnClicked(b, onInsertTrailing, innergrid); + uiGridAppend(innergrid, uiControl(b), + 0, 0, 1, 1, + 1, uiAlignFill, 0, uiAlignFill); + b = uiNewButton("Insert Bottom"); + uiButtonOnClicked(b, onInsertBottom, innergrid); + uiGridAppend(innergrid, uiControl(b), + 1, 0, 1, 1, + 1, uiAlignFill, 0, uiAlignFill); + b = uiNewButton("Insert Leading"); + uiButtonOnClicked(b, onInsertLeading, innergrid); + uiGridAppend(innergrid, uiControl(b), + 1, 1, 1, 1, + 1, uiAlignFill, 0, uiAlignFill); + b = uiNewButton("Insert Top"); + uiButtonOnClicked(b, onInsertTop, innergrid); + uiGridAppend(innergrid, uiControl(b), + 0, 1, 1, 1, + 1, uiAlignFill, 0, uiAlignFill); + uiGridAppend(outergrid, uiControl(innergrid), + 1, 0, 1, 1, + 1, uiAlignFill, 1, uiAlignFill); + + innergrid = newGrid(); + uiGridAppend(innergrid, uiControl(uiNewColorButton()), + 0, 0, 1, 1, + 1, uiAlignFill, 0, uiAlignFill); + uiGridAppend(innergrid, uiControl(uiNewColorButton()), + 0, 1, 1, 1, + 1, uiAlignStart, 0, uiAlignFill); + uiGridAppend(innergrid, uiControl(uiNewColorButton()), + 0, 2, 1, 1, + 1, uiAlignCenter, 0, uiAlignFill); + uiGridAppend(innergrid, uiControl(uiNewColorButton()), + 0, 3, 1, 1, + 1, uiAlignEnd, 0, uiAlignFill); + uiGridAppend(outergrid, uiControl(innergrid), + 0, 1, 1, 1, + 1, uiAlignFill, 1, uiAlignFill); + + // TODO with only this, wrong size on OS X — expand sizing thing? + innergrid = newGrid(); + uiGridAppend(innergrid, uiControl(uiNewColorButton()), + 0, 0, 1, 1, + 0, uiAlignFill, 1, uiAlignFill); + uiGridAppend(innergrid, uiControl(uiNewColorButton()), + 1, 0, 1, 1, + 0, uiAlignFill, 1, uiAlignStart); + uiGridAppend(innergrid, uiControl(uiNewColorButton()), + 2, 0, 1, 1, + 0, uiAlignFill, 1, uiAlignCenter); + uiGridAppend(innergrid, uiControl(uiNewColorButton()), + 3, 0, 1, 1, + 0, uiAlignFill, 1, uiAlignEnd); + uiGridAppend(outergrid, uiControl(innergrid), + 1, 1, 1, 1, + 1, uiAlignFill, 1, uiAlignFill); + + return uiControl(outergrid); +} + +static const struct { + const char *name; + uiControl *(*f)(void); +} pages[] = { + // based on GTK+ test/testgrid.c + { "Simple Grid", simpleGrid }, + { "Box Comparison", boxComparison }, + { "Empty Line", emptyLine }, + { "Empty Grid", emptyGrid }, + { "Spanning Grid", spanningGrid }, + // my own + { "Assorted", assorted }, + { NULL, NULL }, +}; + +uiTab *makePage14(void) +{ + uiTab *page14; + int i; + + page14 = newTab(); + + for (i = 0; pages[i].name != NULL; i++) + uiTabAppend(page14, + pages[i].name, + (*(pages[i].f))()); + + return page14; +} diff --git a/dep/libui/test/page15.c b/dep/libui/test/page15.c new file mode 100644 index 0000000..e703bee --- /dev/null +++ b/dep/libui/test/page15.c @@ -0,0 +1,260 @@ +// 15 june 2016 +#include "test.h" + +static uiAreaHandler borderAH; +static int borderAHInit = 0; +static double lastx = -1, lasty = -1; + +struct trect { + double left; + double top; + double right; + double bottom; + int in; +}; + +#define tsetrect(re, l, t, r, b) re.left = l; re.top = t; re.right = r; re.bottom = b; re.in = lastx >= re.left && lastx < re.right && lasty >= re.top && lasty < re.bottom + +struct tareas { + struct trect move; + struct trect alsomove; + struct trect leftresize; + struct trect topresize; + struct trect rightresize; + struct trect bottomresize; + struct trect topleftresize; + struct trect toprightresize; + struct trect bottomleftresize; + struct trect bottomrightresize; + struct trect close; +}; + +static void filltareas(double awid, double aht, struct tareas *ta) +{ + tsetrect(ta->move, 20, 20, awid - 20, 20 + 30); + tsetrect(ta->alsomove, 30, 200, 100, 270); + tsetrect(ta->leftresize, 5, 20, 15, aht - 20); + tsetrect(ta->topresize, 20, 5, awid - 20, 15); + tsetrect(ta->rightresize, awid - 15, 20, awid - 5, aht - 20); + tsetrect(ta->bottomresize, 20, aht - 15, awid - 20, aht - 5); + tsetrect(ta->topleftresize, 5, 5, 15, 15); + tsetrect(ta->toprightresize, awid - 15, 5, awid - 5, 15); + tsetrect(ta->bottomleftresize, 5, aht - 15, 15, aht - 5); + tsetrect(ta->bottomrightresize, awid - 15, aht - 15, awid - 5, aht - 5); + tsetrect(ta->close, 130, 200, 200, 270); +} + +static void drawtrect(uiDrawContext *c, struct trect tr, double r, double g, double bl) +{ + uiDrawPath *p; + uiDrawBrush b; + + memset(&b, 0, sizeof (uiDrawBrush)); + b.Type = uiDrawBrushTypeSolid; + b.R = r; + b.G = g; + b.B = bl; + b.A = 1.0; + if (tr.in) { + b.R += b.R * 0.75; + b.G += b.G * 0.75; + b.B += b.B * 0.75; + } + p = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathAddRectangle(p, + tr.left, + tr.top, + tr.right - tr.left, + tr.bottom - tr.top); + uiDrawPathEnd(p); + uiDrawFill(c, p, &b); + uiDrawFreePath(p); +} + +static void handlerDraw(uiAreaHandler *a, uiArea *area, uiAreaDrawParams *p) +{ + struct tareas ta; + + filltareas(p->AreaWidth, p->AreaHeight, &ta); + drawtrect(p->Context, ta.move, 0, 0.5, 0); + drawtrect(p->Context, ta.alsomove, 0, 0.5, 0); + drawtrect(p->Context, ta.leftresize, 0, 0, 0.5); + drawtrect(p->Context, ta.topresize, 0, 0, 0.5); + drawtrect(p->Context, ta.rightresize, 0, 0, 0.5); + drawtrect(p->Context, ta.bottomresize, 0, 0, 0.5); + drawtrect(p->Context, ta.topleftresize, 0, 0.5, 0.5); + drawtrect(p->Context, ta.toprightresize, 0, 0.5, 0.5); + drawtrect(p->Context, ta.bottomleftresize, 0, 0.5, 0.5); + drawtrect(p->Context, ta.bottomrightresize, 0, 0.5, 0.5); + drawtrect(p->Context, ta.close, 0.5, 0, 0); + + // TODO add current position prints here +} + +static void handlerMouseEvent(uiAreaHandler *a, uiArea *area, uiAreaMouseEvent *e) +{ + struct tareas ta; + + lastx = e->X; + lasty = e->Y; + filltareas(e->AreaWidth, e->AreaHeight, &ta); + // redraw our highlighted rect + uiAreaQueueRedrawAll(area); + if (e->Down != 1) + return; + if (ta.move.in || ta.alsomove.in) { + uiAreaBeginUserWindowMove(area); + return; + } +#define resize(cond, edge) if (cond) { uiAreaBeginUserWindowResize(area, edge); return; } + resize(ta.leftresize.in, uiWindowResizeEdgeLeft) + resize(ta.topresize.in, uiWindowResizeEdgeTop) + resize(ta.rightresize.in, uiWindowResizeEdgeRight) + resize(ta.bottomresize.in, uiWindowResizeEdgeBottom) + resize(ta.topleftresize.in, uiWindowResizeEdgeTopLeft) + resize(ta.toprightresize.in, uiWindowResizeEdgeTopRight) + resize(ta.bottomleftresize.in, uiWindowResizeEdgeBottomLeft) + resize(ta.bottomrightresize.in, uiWindowResizeEdgeBottomRight) + if (ta.close.in) { + // TODO + return; + } +} + +static void handlerMouseCrossed(uiAreaHandler *ah, uiArea *a, int left) +{ +} + +static void handlerDragBroken(uiAreaHandler *ah, uiArea *a) +{ +} + +static int handlerKeyEvent(uiAreaHandler *ah, uiArea *a, uiAreaKeyEvent *e) +{ + return 0; +} + +static void borderWindowOpen(uiButton *b, void *data) +{ + uiWindow *w; + uiArea *a; + + if (!borderAHInit) { + borderAH.Draw = handlerDraw; + borderAH.MouseEvent = handlerMouseEvent; + borderAH.MouseCrossed = handlerMouseCrossed; + borderAH.DragBroken = handlerDragBroken; + borderAH.KeyEvent = handlerKeyEvent; + borderAHInit = 1; + } + + w = uiNewWindow("Border Resize Test", 300, 500, 0); + uiWindowSetBorderless(w, 1); + + a = uiNewArea(&borderAH); +// uiWindowSetChild(w, uiControl(a)); +{uiBox *b; +b=uiNewHorizontalBox(); +uiBoxAppend(b,uiControl(a),1); +uiWindowSetChild(w,uiControl(b));} +//TODO why is this hack needed? GTK+ issue + + uiControlShow(uiControl(w)); +} + +static uiSpinbox *width, *height; +static uiCheckbox *fullscreen; + +static void sizeWidth(uiSpinbox *s, void *data) +{ + uiWindow *w = uiWindow(data); + int xp, yp; + + uiWindowContentSize(w, &xp, &yp); + xp = uiSpinboxValue(width); + uiWindowSetContentSize(w, xp, yp); +} + +static void sizeHeight(uiSpinbox *s, void *data) +{ + uiWindow *w = uiWindow(data); + int xp, yp; + + uiWindowContentSize(w, &xp, &yp); + yp = uiSpinboxValue(height); + uiWindowSetContentSize(w, xp, yp); +} + +static void updatesize(uiWindow *w) +{ + int xp, yp; + + uiWindowContentSize(w, &xp, &yp); + uiSpinboxSetValue(width, xp); + uiSpinboxSetValue(height, yp); + // TODO on OS X this is updated AFTER sending the size change, not before + uiCheckboxSetChecked(fullscreen, uiWindowFullscreen(w)); +} + +void onSize(uiWindow *w, void *data) +{ + printf("size\n"); + updatesize(w); +} + +void setFullscreen(uiCheckbox *cb, void *data) +{ + uiWindow *w = uiWindow(data); + + uiWindowSetFullscreen(w, uiCheckboxChecked(fullscreen)); + updatesize(w); +} + +static void borderless(uiCheckbox *c, void *data) +{ + uiWindow *w = uiWindow(data); + + uiWindowSetBorderless(w, uiCheckboxChecked(c)); +} + +uiBox *makePage15(uiWindow *w) +{ + uiBox *page15; + uiBox *hbox; + uiButton *button; + uiCheckbox *checkbox; + + page15 = newVerticalBox(); + + hbox = newHorizontalBox(); + uiBoxAppend(page15, uiControl(hbox), 0); + + uiBoxAppend(hbox, uiControl(uiNewLabel("Size")), 0); + width = uiNewSpinbox(INT_MIN, INT_MAX); + uiBoxAppend(hbox, uiControl(width), 1); + height = uiNewSpinbox(INT_MIN, INT_MAX); + uiBoxAppend(hbox, uiControl(height), 1); + fullscreen = uiNewCheckbox("Fullscreen"); + uiBoxAppend(hbox, uiControl(fullscreen), 0); + + uiSpinboxOnChanged(width, sizeWidth, w); + uiSpinboxOnChanged(height, sizeHeight, w); + uiCheckboxOnToggled(fullscreen, setFullscreen, w); + uiWindowOnContentSizeChanged(w, onSize, NULL); + updatesize(w); + + checkbox = uiNewCheckbox("Borderless"); + uiCheckboxOnToggled(checkbox, borderless, w); + uiBoxAppend(page15, uiControl(checkbox), 0); + + button = uiNewButton("Borderless Resizes"); + uiButtonOnClicked(button, borderWindowOpen, NULL); + uiBoxAppend(page15, uiControl(button), 0); + + hbox = newHorizontalBox(); + uiBoxAppend(page15, uiControl(hbox), 1); + + uiBoxAppend(hbox, uiControl(uiNewVerticalSeparator()), 0); + + return page15; +} diff --git a/dep/libui/test/page16.c b/dep/libui/test/page16.c new file mode 100644 index 0000000..f28ba3c --- /dev/null +++ b/dep/libui/test/page16.c @@ -0,0 +1,163 @@ +// 21 june 2016 +#include "test.h" + +static uiTableModelHandler mh; + +static int modelNumColumns(uiTableModelHandler *mh, uiTableModel *m) +{ + return 9; +} + +static uiTableValueType modelColumnType(uiTableModelHandler *mh, uiTableModel *m, int column) +{ + if (column == 3 || column == 4) + return uiTableValueTypeColor; + if (column == 5) + return uiTableValueTypeImage; + if (column == 7 || column == 8) + return uiTableValueTypeInt; + return uiTableValueTypeString; +} + +static int modelNumRows(uiTableModelHandler *mh, uiTableModel *m) +{ + return 15; +} + +static uiImage *img[2]; +static char row9text[1024]; +static int yellowRow = -1; +static int checkStates[15]; + +static uiTableValue *modelCellValue(uiTableModelHandler *mh, uiTableModel *m, int row, int col) +{ + char buf[256]; + + if (col == 3) { + if (row == yellowRow) + return uiNewTableValueColor(1, 1, 0, 1); + if (row == 3) + return uiNewTableValueColor(1, 0, 0, 1); + if (row == 11) + return uiNewTableValueColor(0, 0.5, 1, 0.5); + return NULL; + } + if (col == 4) { + if ((row % 2) == 1) + return uiNewTableValueColor(0.5, 0, 0.75, 1); + return NULL; + } + if (col == 5) { + if (row < 8) + return uiNewTableValueImage(img[0]); + return uiNewTableValueImage(img[1]); + } + if (col == 7) + return uiNewTableValueInt(checkStates[row]); + if (col == 8) { + if (row == 0) + return uiNewTableValueInt(0); + if (row == 13) + return uiNewTableValueInt(100); + if (row == 14) + return uiNewTableValueInt(-1); + return uiNewTableValueInt(50); + } + switch (col) { + case 0: + sprintf(buf, "Row %d", row); + break; + case 2: + if (row == 9) + return uiNewTableValueString(row9text); + // fall through + case 1: + strcpy(buf, "Part"); + break; + case 6: + strcpy(buf, "Make Yellow"); + break; + } + return uiNewTableValueString(buf); +} + +static void modelSetCellValue(uiTableModelHandler *mh, uiTableModel *m, int row, int col, const uiTableValue *val) +{ + if (row == 9 && col == 2) + strcpy(row9text, uiTableValueString(val)); + if (col == 6) { + int prevYellowRow; + + prevYellowRow = yellowRow; + yellowRow = row; + if (prevYellowRow != -1) + uiTableModelRowChanged(m, prevYellowRow); + uiTableModelRowChanged(m, yellowRow); + } + if (col == 7) + checkStates[row] = uiTableValueInt(val); +} + +static uiTableModel *m; + +uiBox *makePage16(void) +{ + uiBox *page16; + uiTable *t; + uiTableParams p; + uiTableTextColumnOptionalParams tp; + + img[0] = uiNewImage(16, 16); + appendImageNamed(img[0], "andlabs_16x16test_24june2016.png"); + appendImageNamed(img[0], "andlabs_32x32test_24june2016.png"); + img[1] = uiNewImage(16, 16); + appendImageNamed(img[1], "tango-icon-theme-0.8.90_16x16_x-office-spreadsheet.png"); + appendImageNamed(img[1], "tango-icon-theme-0.8.90_32x32_x-office-spreadsheet.png"); + + strcpy(row9text, "Part"); + + memset(checkStates, 0, 15 * sizeof (int)); + + page16 = newVerticalBox(); + + mh.NumColumns = modelNumColumns; + mh.ColumnType = modelColumnType; + mh.NumRows = modelNumRows; + mh.CellValue = modelCellValue; + mh.SetCellValue = modelSetCellValue; + m = uiNewTableModel(&mh); + + memset(&p, 0, sizeof (uiTableParams)); + p.Model = m; + p.RowBackgroundColorModelColumn = 3; + t = uiNewTable(&p); + uiBoxAppend(page16, uiControl(t), 1); + + uiTableAppendTextColumn(t, "Column 1", + 0, uiTableModelColumnNeverEditable, NULL); + + memset(&tp, 0, sizeof (uiTableTextColumnOptionalParams)); + tp.ColorModelColumn = 4; + uiTableAppendImageTextColumn(t, "Column 2", + 5, + 1, uiTableModelColumnNeverEditable, &tp); + uiTableAppendTextColumn(t, "Editable", + 2, uiTableModelColumnAlwaysEditable, NULL); + + uiTableAppendCheckboxColumn(t, "Checkboxes", + 7, uiTableModelColumnAlwaysEditable); + uiTableAppendButtonColumn(t, "Buttons", + 6, uiTableModelColumnAlwaysEditable); + + uiTableAppendProgressBarColumn(t, "Progress Bar", + 8); + + return page16; +} + +void freePage16(void) +{ + uiFreeTableModel(m); + uiFreeImage(img[1]); + uiFreeImage(img[0]); +} diff --git a/dep/libui/test/page2.c b/dep/libui/test/page2.c new file mode 100644 index 0000000..abb0648 --- /dev/null +++ b/dep/libui/test/page2.c @@ -0,0 +1,215 @@ +// 29 april 2015 +#include "test.h" + +uiGroup *page2group; + +static uiLabel *movingLabel; +static uiBox *movingBoxes[2]; +static int movingCurrent; + +static void moveLabel(uiButton *b, void *data) +{ + int from, to; + + from = movingCurrent; + to = 0; + if (from == 0) + to = 1; + uiBoxDelete(movingBoxes[from], 0); + uiBoxAppend(movingBoxes[to], uiControl(movingLabel), 0); + movingCurrent = to; +} + +static int moveBack; +#define moveOutText "Move Page 1 Out" +#define moveBackText "Move Page 1 Back" + +static void movePage1(uiButton *b, void *data) +{ + if (moveBack) { + uiBoxDelete(mainBox, 1); + uiTabInsertAt(mainTab, "Page 1", 0, uiControl(page1)); + uiButtonSetText(b, moveOutText); + moveBack = 0; + return; + } + uiTabDelete(mainTab, 0); + uiBoxAppend(mainBox, uiControl(page1), 1); + uiButtonSetText(b, moveBackText); + moveBack = 1; +} + +static void openAnotherWindow(uiButton *bb, void *data) +{ + uiWindow *w; + uiBox *b; + + w = uiNewWindow("Another Window", 100, 100, data != NULL); + if (data != NULL) { + b = uiNewVerticalBox(); + uiBoxAppend(b, uiControl(uiNewEntry()), 0); + uiBoxAppend(b, uiControl(uiNewButton("Button")), 0); + uiBoxSetPadded(b, 1); + uiWindowSetChild(w, uiControl(b)); + } else + uiWindowSetChild(w, uiControl(makePage6())); + uiWindowSetMargined(w, 1); + uiControlShow(uiControl(w)); +} + +static void openAnotherDisabledWindow(uiButton *b, void *data) +{ + uiWindow *w; + + w = uiNewWindow("Another Window", 100, 100, data != NULL); + uiControlDisable(uiControl(w)); + uiControlShow(uiControl(w)); +} + +#define SHED(method, Method) \ + static void method ## Control(uiButton *b, void *data) \ + { \ + uiControl ## Method(uiControl(data)); \ + } +SHED(show, Show) +SHED(enable, Enable) +SHED(disable, Disable) + +static void echoReadOnlyText(uiEntry *e, void *data) +{ + char *text; + + text = uiEntryText(e); + uiEntrySetText(uiEntry(data), text); + uiFreeText(text); +} + +uiBox *makePage2(void) +{ + uiBox *page2; + uiBox *hbox; + uiGroup *group; + uiBox *vbox; + uiButton *button; + uiBox *nestedBox; + uiBox *innerhbox; + uiBox *innerhbox2; + uiBox *innerhbox3; + uiTab *disabledTab; + uiEntry *entry; + uiEntry *readonly; + uiButton *button2; + + page2 = newVerticalBox(); + + group = newGroup("Moving Label"); + page2group = group; + uiBoxAppend(page2, uiControl(group), 0); + vbox = newVerticalBox(); + uiGroupSetChild(group, uiControl(vbox)); + + hbox = newHorizontalBox(); + button = uiNewButton("Move the Label!"); + uiButtonOnClicked(button, moveLabel, NULL); + uiBoxAppend(hbox, uiControl(button), 1); + // have a blank label for space + uiBoxAppend(hbox, uiControl(uiNewLabel("")), 1); + uiBoxAppend(vbox, uiControl(hbox), 0); + + hbox = newHorizontalBox(); + movingBoxes[0] = newVerticalBox(); + uiBoxAppend(hbox, uiControl(movingBoxes[0]), 1); + movingBoxes[1] = newVerticalBox(); + uiBoxAppend(hbox, uiControl(movingBoxes[1]), 1); + uiBoxAppend(vbox, uiControl(hbox), 0); + + movingCurrent = 0; + movingLabel = uiNewLabel("This label moves!"); + uiBoxAppend(movingBoxes[movingCurrent], uiControl(movingLabel), 0); + + hbox = newHorizontalBox(); + button = uiNewButton(moveOutText); + uiButtonOnClicked(button, movePage1, NULL); + uiBoxAppend(hbox, uiControl(button), 0); + uiBoxAppend(page2, uiControl(hbox), 0); + moveBack = 0; + + hbox = newHorizontalBox(); + uiBoxAppend(hbox, uiControl(uiNewLabel("Label Alignment Test")), 0); + button = uiNewButton("Open Menued Window"); + uiButtonOnClicked(button, openAnotherWindow, button); + uiBoxAppend(hbox, uiControl(button), 0); + button = uiNewButton("Open Menuless Window"); + uiButtonOnClicked(button, openAnotherWindow, NULL); + uiBoxAppend(hbox, uiControl(button), 0); + button = uiNewButton("Disabled Menued"); + uiButtonOnClicked(button, openAnotherDisabledWindow, button); + uiBoxAppend(hbox, uiControl(button), 0); + button = uiNewButton("Disabled Menuless"); + uiButtonOnClicked(button, openAnotherDisabledWindow, NULL); + uiBoxAppend(hbox, uiControl(button), 0); + uiBoxAppend(page2, uiControl(hbox), 0); + + nestedBox = newHorizontalBox(); + innerhbox = newHorizontalBox(); + uiBoxAppend(innerhbox, uiControl(uiNewButton("These")), 0); + button = uiNewButton("buttons"); + uiControlDisable(uiControl(button)); + uiBoxAppend(innerhbox, uiControl(button), 0); + uiBoxAppend(nestedBox, uiControl(innerhbox), 0); + innerhbox = newHorizontalBox(); + uiBoxAppend(innerhbox, uiControl(uiNewButton("are")), 0); + innerhbox2 = newHorizontalBox(); + button = uiNewButton("in"); + uiControlDisable(uiControl(button)); + uiBoxAppend(innerhbox2, uiControl(button), 0); + uiBoxAppend(innerhbox, uiControl(innerhbox2), 0); + uiBoxAppend(nestedBox, uiControl(innerhbox), 0); + innerhbox = newHorizontalBox(); + innerhbox2 = newHorizontalBox(); + uiBoxAppend(innerhbox2, uiControl(uiNewButton("nested")), 0); + innerhbox3 = newHorizontalBox(); + button = uiNewButton("boxes"); + uiControlDisable(uiControl(button)); + uiBoxAppend(innerhbox3, uiControl(button), 0); + uiBoxAppend(innerhbox2, uiControl(innerhbox3), 0); + uiBoxAppend(innerhbox, uiControl(innerhbox2), 0); + uiBoxAppend(nestedBox, uiControl(innerhbox), 0); + uiBoxAppend(page2, uiControl(nestedBox), 0); + + hbox = newHorizontalBox(); + button = uiNewButton("Enable Nested Box"); + uiButtonOnClicked(button, enableControl, nestedBox); + uiBoxAppend(hbox, uiControl(button), 0); + button = uiNewButton("Disable Nested Box"); + uiButtonOnClicked(button, disableControl, nestedBox); + uiBoxAppend(hbox, uiControl(button), 0); + uiBoxAppend(page2, uiControl(hbox), 0); + + disabledTab = newTab(); + uiTabAppend(disabledTab, "Disabled", uiControl(uiNewButton("Button"))); + uiTabAppend(disabledTab, "Tab", uiControl(uiNewLabel("Label"))); + uiControlDisable(uiControl(disabledTab)); + uiBoxAppend(page2, uiControl(disabledTab), 1); + + entry = uiNewEntry(); + readonly = uiNewEntry(); + uiEntryOnChanged(entry, echoReadOnlyText, readonly); + uiEntrySetText(readonly, "If you can see this, uiEntryReadOnly() isn't working properly."); + uiEntrySetReadOnly(readonly, 1); + if (uiEntryReadOnly(readonly)) + uiEntrySetText(readonly, ""); + uiBoxAppend(page2, uiControl(entry), 0); + uiBoxAppend(page2, uiControl(readonly), 0); + + hbox = newHorizontalBox(); + button = uiNewButton("Show Button 2"); + button2 = uiNewButton("Button 2"); + uiButtonOnClicked(button, showControl, button2); + uiControlHide(uiControl(button2)); + uiBoxAppend(hbox, uiControl(button), 1); + uiBoxAppend(hbox, uiControl(button2), 0); + uiBoxAppend(page2, uiControl(hbox), 0); + + return page2; +} diff --git a/dep/libui/test/page3.c b/dep/libui/test/page3.c new file mode 100644 index 0000000..1f229e9 --- /dev/null +++ b/dep/libui/test/page3.c @@ -0,0 +1,69 @@ +// 7 may 2015 +#include "test.h" + +static uiBox *makeSet(int omit, int hidden, int stretch) +{ + uiBox *hbox; + uiButton *buttons[4]; + + // don't use newHorizontalBox() + // the point of this test is to test hidden controls and padded + hbox = (*newhbox)(); + uiBoxSetPadded(hbox, 1); + if (omit != 0) { + buttons[0] = uiNewButton("First"); + uiBoxAppend(hbox, uiControl(buttons[0]), stretch); + } + if (omit != 1) { + buttons[1] = uiNewButton("Second"); + uiBoxAppend(hbox, uiControl(buttons[1]), stretch); + } + if (omit != 2) { + buttons[2] = uiNewButton("Third"); + uiBoxAppend(hbox, uiControl(buttons[2]), stretch); + } + if (omit != 3) { + buttons[3] = uiNewButton("Fourth"); + uiBoxAppend(hbox, uiControl(buttons[3]), stretch); + } + if (hidden != -1) + uiControlHide(uiControl(buttons[hidden])); + return hbox; +} + +uiBox *makePage3(void) +{ + uiBox *page3; + uiBox *hbox; + uiBox *hbox2; + uiBox *vbox; + int hidden; + + page3 = newVerticalBox(); + + // first the non-stretchy type + for (hidden = 0; hidden < 4; hidden++) { + // these two must stay unpadded as well, otherwise the test isn't meaningful + hbox2 = (*newhbox)(); + vbox = (*newvbox)(); + // reference set + hbox = makeSet(hidden, -1, 0); + uiBoxAppend(vbox, uiControl(hbox), 0); + // real thing + hbox = makeSet(-1, hidden, 0); + uiBoxAppend(vbox, uiControl(hbox), 0); + // pack vbox in + uiBoxAppend(hbox2, uiControl(vbox), 0); + // and have a button in there for showing right margins + uiBoxAppend(hbox2, uiControl(uiNewButton("Right Margin Test")), 1); + uiBoxAppend(page3, uiControl(hbox2), 0); + } + + // then the stretchy type + for (hidden = 0; hidden < 4; hidden++) { + hbox = makeSet(-1, hidden, 1); + uiBoxAppend(page3, uiControl(hbox), 0); + } + + return page3; +} diff --git a/dep/libui/test/page4.c b/dep/libui/test/page4.c new file mode 100644 index 0000000..ce4a6af --- /dev/null +++ b/dep/libui/test/page4.c @@ -0,0 +1,165 @@ +// 19 may 2015 +#include "test.h" + +static uiSpinbox *spinbox; +static uiSlider *slider; +static uiProgressBar *pbar; + +#define CHANGED(what) \ + static void on ## what ## Changed(ui ## what *this, void *data) \ + { \ + int value; \ + printf("on %s changed\n", #what); \ + value = ui ## what ## Value(this); \ + uiSpinboxSetValue(spinbox, value); \ + uiSliderSetValue(slider, value); \ + uiProgressBarSetValue(pbar, value); \ + } +CHANGED(Spinbox) +CHANGED(Slider) + +#define SETTOO(what, name, n) \ + static void set ## what ## Too ## name(uiButton *this, void *data) \ + { \ + ui ## what ## SetValue(ui ## what(data), n); \ + } +SETTOO(Spinbox, Low, -80) +SETTOO(Spinbox, High, 80) +SETTOO(Slider, Low, -80) +SETTOO(Slider, High, 80) + +static uiCombobox *cbox; +static uiEditableCombobox *editable; +static uiRadioButtons *rb; + +static void appendCBRB(uiButton *b, void *data) +{ + uiComboboxAppend(cbox, "New Item"); + uiEditableComboboxAppend(editable, "New Item"); + uiRadioButtonsAppend(rb, "New Item"); +} + +static void onCBChanged(uiCombobox *c, void *data) +{ + printf("%s combobox changed to %d\n", + (char *) data, + (int) uiComboboxSelected(c)); + uiEditableComboboxSetText(editable, "changed"); +} + +static void onECBChanged(uiEditableCombobox *c, void *data) +{ + char *t; + + t = uiEditableComboboxText(c); + printf("%s combobox changed to %s\n", + (char *) data, + t); + uiFreeText(t); +} + +static void onRBSelected(uiRadioButtons *r, void *data) +{ + printf("radio buttons %d\n", uiRadioButtonsSelected(r)); +} + +static void selectSecond(uiButton *b, void *data) +{ + // TODO combobox, editable + uiRadioButtonsSetSelected(rb, 1); +} + +static void selectNone(uiButton *b, void *data) +{ + // TODO combobox, editable + uiRadioButtonsSetSelected(rb, -1); +} + +uiBox *makePage4(void) +{ + uiBox *page4; + uiBox *hbox; + uiSpinbox *xsb; + uiButton *b; + uiSlider *xsl; + + page4 = newVerticalBox(); + + spinbox = uiNewSpinbox(0, 100); + uiSpinboxOnChanged(spinbox, onSpinboxChanged, NULL); + uiBoxAppend(page4, uiControl(spinbox), 0); + + slider = uiNewSlider(0, 100); + uiSliderOnChanged(slider, onSliderChanged, NULL); + uiBoxAppend(page4, uiControl(slider), 0); + + pbar = uiNewProgressBar(); + uiBoxAppend(page4, uiControl(pbar), 0); + + uiBoxAppend(page4, uiControl(uiNewHorizontalSeparator()), 0); + + hbox = newHorizontalBox(); + xsb = uiNewSpinbox(-40, 40); + uiBoxAppend(hbox, uiControl(xsb), 0); + b = uiNewButton("Bad Low"); + uiButtonOnClicked(b, setSpinboxTooLow, xsb); + uiBoxAppend(hbox, uiControl(b), 0); + b = uiNewButton("Bad High"); + uiButtonOnClicked(b, setSpinboxTooHigh, xsb); + uiBoxAppend(hbox, uiControl(b), 0); + uiBoxAppend(page4, uiControl(hbox), 0); + + hbox = newHorizontalBox(); + xsl = uiNewSlider(-40, 40); + uiBoxAppend(hbox, uiControl(xsl), 0); + b = uiNewButton("Bad Low"); + uiButtonOnClicked(b, setSliderTooLow, xsl); + uiBoxAppend(hbox, uiControl(b), 0); + b = uiNewButton("Bad High"); + uiButtonOnClicked(b, setSliderTooHigh, xsl); + uiBoxAppend(hbox, uiControl(b), 0); + uiBoxAppend(page4, uiControl(hbox), 0); + + uiBoxAppend(page4, uiControl(uiNewHorizontalSeparator()), 0); + + cbox = uiNewCombobox(); + uiComboboxAppend(cbox, "Item 1"); + uiComboboxAppend(cbox, "Item 2"); + uiComboboxAppend(cbox, "Item 3"); + uiComboboxOnSelected(cbox, onCBChanged, "noneditable"); + uiBoxAppend(page4, uiControl(cbox), 0); + + editable = uiNewEditableCombobox(); + uiEditableComboboxAppend(editable, "Editable Item 1"); + uiEditableComboboxAppend(editable, "Editable Item 2"); + uiEditableComboboxAppend(editable, "Editable Item 3"); + uiEditableComboboxOnChanged(editable, onECBChanged, "editable"); + uiBoxAppend(page4, uiControl(editable), 0); + + rb = uiNewRadioButtons(); + uiRadioButtonsAppend(rb, "Item 1"); + uiRadioButtonsAppend(rb, "Item 2"); + uiRadioButtonsAppend(rb, "Item 3"); + uiRadioButtonsOnSelected(rb, onRBSelected, NULL); + uiBoxAppend(page4, uiControl(rb), 0); + + hbox = newHorizontalBox(); + b = uiNewButton("Append"); + uiButtonOnClicked(b, appendCBRB, NULL); + uiBoxAppend(hbox, uiControl(b), 0); + b = uiNewButton("Second"); + uiButtonOnClicked(b, selectSecond, NULL); + uiBoxAppend(hbox, uiControl(b), 0); + b = uiNewButton("None"); + uiButtonOnClicked(b, selectNone, NULL); + uiBoxAppend(hbox, uiControl(b), 0); + uiBoxAppend(page4, uiControl(hbox), 0); + + uiBoxAppend(page4, uiControl(uiNewHorizontalSeparator()), 0); + + uiBoxAppend(page4, uiControl(uiNewDateTimePicker()), 0); + uiBoxAppend(page4, uiControl(uiNewDatePicker()), 0); + uiBoxAppend(page4, uiControl(uiNewTimePicker()), 0); + + return page4; +} diff --git a/dep/libui/test/page5.c b/dep/libui/test/page5.c new file mode 100644 index 0000000..9bc1105 --- /dev/null +++ b/dep/libui/test/page5.c @@ -0,0 +1,99 @@ +// 22 may 2015 +#include "test.h" + +static uiWindow *parent; + +static void openFile(uiButton *b, void *data) +{ + char *fn; + + fn = uiOpenFile(parent); + if (fn == NULL) + uiLabelSetText(uiLabel(data), "(cancelled)"); + else { + uiLabelSetText(uiLabel(data), fn); + uiFreeText(fn); + } +} + +static void saveFile(uiButton *b, void *data) +{ + char *fn; + + fn = uiSaveFile(parent); + if (fn == NULL) + uiLabelSetText(uiLabel(data), "(cancelled)"); + else { + uiLabelSetText(uiLabel(data), fn); + uiFreeText(fn); + } +} + +static uiEntry *title, *description; + +static void msgBox(uiButton *b, void *data) +{ + char *t, *d; + + t = uiEntryText(title); + d = uiEntryText(description); + uiMsgBox(parent, t, d); + uiFreeText(d); + uiFreeText(t); +} + +static void msgBoxError(uiButton *b, void *data) +{ + char *t, *d; + + t = uiEntryText(title); + d = uiEntryText(description); + uiMsgBoxError(parent, t, d); + uiFreeText(d); + uiFreeText(t); +} + +uiBox *makePage5(uiWindow *pw) +{ + uiBox *page5; + uiBox *hbox; + uiButton *button; + uiLabel *label; + + parent = pw; + + page5 = newVerticalBox(); + +#define D(n, f) \ + hbox = newHorizontalBox(); \ + button = uiNewButton(n); \ + label = uiNewLabel(""); \ + uiButtonOnClicked(button, f, label); \ + uiBoxAppend(hbox, uiControl(button), 0); \ + uiBoxAppend(hbox, uiControl(label), 0); \ + uiBoxAppend(page5, uiControl(hbox), 0); + + D("Open File", openFile); + D("Save File", saveFile); + + title = uiNewEntry(); + uiEntrySetText(title, "Title"); + description = uiNewEntry(); + uiEntrySetText(description, "Description"); + + hbox = newHorizontalBox(); + button = uiNewButton("Message Box"); + uiButtonOnClicked(button, msgBox, NULL); + uiBoxAppend(hbox, uiControl(button), 0); + uiBoxAppend(hbox, uiControl(title), 0); + uiBoxAppend(page5, uiControl(hbox), 0); + + hbox = newHorizontalBox(); + button = uiNewButton("Error Box"); + uiButtonOnClicked(button, msgBoxError, NULL); + uiBoxAppend(hbox, uiControl(button), 0); + uiBoxAppend(hbox, uiControl(description), 0); + uiBoxAppend(page5, uiControl(hbox), 0); + + return page5; +} diff --git a/dep/libui/test/page6.c b/dep/libui/test/page6.c new file mode 100644 index 0000000..896b3d5 --- /dev/null +++ b/dep/libui/test/page6.c @@ -0,0 +1,126 @@ +// 8 october 2015 +#include +#include "test.h" + +static uiArea *area; +static uiCombobox *which; +static uiCheckbox *swallowKeys; + +struct handler { + uiAreaHandler ah; +}; + +static struct handler handler; + +static void handlerDraw(uiAreaHandler *a, uiArea *area, uiAreaDrawParams *p) +{ + runDrawTest(uiComboboxSelected(which), p); +} + +static void handlerMouseEvent(uiAreaHandler *a, uiArea *area, uiAreaMouseEvent *e) +{ + printf("mouse (%g,%g):(%g,%g) down:%d up:%d count:%d mods:%x held:0x%" PRIX64 "\n", + e->X, + e->Y, + e->AreaWidth, + e->AreaHeight, + (int) e->Down, + (int) e->Up, + (int) e->Count, + (uint32_t) e->Modifiers, + e->Held1To64); +} + +static void handlerMouseCrossed(uiAreaHandler *ah, uiArea *a, int left) +{ + printf("mouse crossed %d\n", left); +} + +static void handlerDragBroken(uiAreaHandler *ah, uiArea *a) +{ + printf("drag broken\n"); +} + +static int handlerKeyEvent(uiAreaHandler *ah, uiArea *a, uiAreaKeyEvent *e) +{ + char k[4]; + + k[0] = '\''; + k[1] = e->Key; + k[2] = '\''; + k[3] = '\0'; + if (e->Key == 0) { + k[0] = '0'; + k[1] = '\0'; + } + printf("key key:%s extkey:%d mod:%d mods:%d up:%d\n", + k, + (int) e->ExtKey, + (int) e->Modifier, + (int) e->Modifiers, + e->Up); + return uiCheckboxChecked(swallowKeys); +} + +static void shouldntHappen(uiCombobox *c, void *data) +{ + fprintf(stderr, "YOU SHOULD NOT SEE THIS. If you do, uiComboboxSetSelected() is triggering uiComboboxOnSelected(), which it should not.\n"); +} + +static void redraw(uiCombobox *c, void *data) +{ + uiAreaQueueRedrawAll(area); +} + +static void enableArea(uiButton *b, void *data) +{ + if (data != NULL) + uiControlEnable(uiControl(area)); + else + uiControlDisable(uiControl(area)); +} + +uiBox *makePage6(void) +{ + uiBox *page6; + uiBox *hbox; + uiButton *button; + + handler.ah.Draw = handlerDraw; + handler.ah.MouseEvent = handlerMouseEvent; + handler.ah.MouseCrossed = handlerMouseCrossed; + handler.ah.DragBroken = handlerDragBroken; + handler.ah.KeyEvent = handlerKeyEvent; + + page6 = newVerticalBox(); + + hbox = newHorizontalBox(); + uiBoxAppend(page6, uiControl(hbox), 0); + + which = uiNewCombobox(); + populateComboboxWithTests(which); + // this is to make sure that uiComboboxOnSelected() doesn't trigger with uiComboboxSetSelected() + uiComboboxOnSelected(which, shouldntHappen, NULL); + uiComboboxSetSelected(which, 0); + uiComboboxOnSelected(which, redraw, NULL); + uiBoxAppend(hbox, uiControl(which), 0); + + area = uiNewArea((uiAreaHandler *) (&handler)); + uiBoxAppend(page6, uiControl(area), 1); + + hbox = newHorizontalBox(); + uiBoxAppend(page6, uiControl(hbox), 0); + + swallowKeys = uiNewCheckbox("Consider key events handled"); + uiBoxAppend(hbox, uiControl(swallowKeys), 1); + + button = uiNewButton("Enable"); + uiButtonOnClicked(button, enableArea, button); + uiBoxAppend(hbox, uiControl(button), 0); + + button = uiNewButton("Disable"); + uiButtonOnClicked(button, enableArea, NULL); + uiBoxAppend(hbox, uiControl(button), 0); + + return page6; +} diff --git a/dep/libui/test/page7.c b/dep/libui/test/page7.c new file mode 100644 index 0000000..5cc9114 --- /dev/null +++ b/dep/libui/test/page7.c @@ -0,0 +1,25 @@ +// 13 october 2015 +#include "test.h" + +uiBox *makePage7(void) +{ + uiBox *page7; + uiGroup *group; + uiBox *box2; + + page7 = newHorizontalBox(); + + group = makePage7a(); + uiBoxAppend(page7, uiControl(group), 1); + + box2 = newVerticalBox(); + uiBoxAppend(page7, uiControl(box2), 1); + + group = makePage7b(); + uiBoxAppend(box2, uiControl(group), 1); + + group = makePage7c(); + uiBoxAppend(box2, uiControl(group), 1); + + return page7; +} diff --git a/dep/libui/test/page7a.c b/dep/libui/test/page7a.c new file mode 100644 index 0000000..72e0321 --- /dev/null +++ b/dep/libui/test/page7a.c @@ -0,0 +1,139 @@ +// 13 october 2015 +#include "test.h" + +static uiArea *area; +static uiEntry *startAngle; +static uiEntry *sweep; +static uiCheckbox *negative; +static uiCheckbox *radians; + +struct handler { + uiAreaHandler ah; +}; + +static struct handler handler; + +// based on the cairo arc sample +static void handlerDraw(uiAreaHandler *a, uiArea *area, uiAreaDrawParams *p) +{ + double xc = 128.0; + double yc = 128.0; + double radius = 100.0; + uiDrawBrush source; + uiDrawStrokeParams sp; + uiDrawPath *path; + char *startText; + char *sweepText; + double factor; + + source.Type = uiDrawBrushTypeSolid; + source.R = 0; + source.G = 0; + source.B = 0; + source.A = 1; + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + sp.Dashes = NULL; + sp.NumDashes = 0; + sp.DashPhase = 0; + + startText = uiEntryText(startAngle); + sweepText = uiEntryText(sweep); + + factor = uiPi / 180; + if (uiCheckboxChecked(radians)) + factor = 1; + + sp.Thickness = 10.0; + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(path, xc, yc); + uiDrawPathArcTo(path, + xc, yc, + radius, + atof(startText) * factor, + atof(sweepText) * factor, + uiCheckboxChecked(negative)); + uiDrawPathEnd(path); + uiDrawStroke(p->Context, path, &source, &sp); + uiDrawFreePath(path); + + uiFreeText(startText); + uiFreeText(sweepText); +} + +static void handlerMouseEvent(uiAreaHandler *a, uiArea *area, uiAreaMouseEvent *e) +{ + // do nothing +} + +static void handlerMouseCrossed(uiAreaHandler *ah, uiArea *a, int left) +{ + // do nothing +} + +static void handlerDragBroken(uiAreaHandler *ah, uiArea *a) +{ + // do nothing +} + +static int handlerKeyEvent(uiAreaHandler *ah, uiArea *a, uiAreaKeyEvent *e) +{ + return 0; +} + +static void entryChanged(uiEntry *e, void *data) +{ + uiAreaQueueRedrawAll(area); +} + +static void checkboxToggled(uiCheckbox *c, void *data) +{ + uiAreaQueueRedrawAll(area); +} + +uiGroup *makePage7a(void) +{ + uiGroup *group; + uiBox *box, *box2; + + handler.ah.Draw = handlerDraw; + handler.ah.MouseEvent = handlerMouseEvent; + handler.ah.MouseCrossed = handlerMouseCrossed; + handler.ah.DragBroken = handlerDragBroken; + handler.ah.KeyEvent = handlerKeyEvent; + + group = newGroup("Arc Test"); + + box = newVerticalBox(); + uiGroupSetChild(group, uiControl(box)); + + area = uiNewArea((uiAreaHandler *) (&handler)); + uiBoxAppend(box, uiControl(area), 1); + + box2 = newHorizontalBox(); + uiBoxAppend(box, uiControl(box2), 0); + + uiBoxAppend(box2, uiControl(uiNewLabel("Start Angle")), 0); + startAngle = uiNewEntry(); + uiEntryOnChanged(startAngle, entryChanged, NULL); + uiBoxAppend(box2, uiControl(startAngle), 1); + + box2 = newHorizontalBox(); + uiBoxAppend(box, uiControl(box2), 0); + + uiBoxAppend(box2, uiControl(uiNewLabel("Sweep")), 0); + sweep = uiNewEntry(); + uiEntryOnChanged(sweep, entryChanged, NULL); + uiBoxAppend(box2, uiControl(sweep), 1); + + negative = uiNewCheckbox("Negative"); + uiCheckboxOnToggled(negative, checkboxToggled, NULL); + uiBoxAppend(box, uiControl(negative), 0); + + radians = uiNewCheckbox("Radians"); + uiCheckboxOnToggled(radians, checkboxToggled, NULL); + uiBoxAppend(box, uiControl(radians), 0); + + return group; +} diff --git a/dep/libui/test/page7b.c b/dep/libui/test/page7b.c new file mode 100644 index 0000000..d1f98a7 --- /dev/null +++ b/dep/libui/test/page7b.c @@ -0,0 +1,71 @@ +// 13 october 2015 +#include "test.h" + +static uiArea *area; +static uiCheckbox *label; + +struct handler { + uiAreaHandler ah; +}; + +static struct handler handler; + +static void handlerDraw(uiAreaHandler *a, uiArea *area, uiAreaDrawParams *p) +{ + // do nothing +} + +static void handlerMouseEvent(uiAreaHandler *a, uiArea *area, uiAreaMouseEvent *e) +{ + char pos[128]; + + // wonderful, vanilla snprintf() isn't in visual studio 2013 - http://blogs.msdn.com/b/vcblog/archive/2013/07/19/c99-library-support-in-visual-studio-2013.aspx + // we can't use _snprintf() in the test suite because that's msvc-only, so oops. sprintf() it is. + sprintf(pos, "X %g Y %g", e->X, e->Y); + uiCheckboxSetText(label, pos); +} + +static void handlerMouseCrossed(uiAreaHandler *ah, uiArea *a, int left) +{ +printf("%d %d\n", left, !left); + uiCheckboxSetChecked(label, !left); +} + +static void handlerDragBroken(uiAreaHandler *ah, uiArea *a) +{ + // do nothing +} + +static int handlerKeyEvent(uiAreaHandler *ah, uiArea *a, uiAreaKeyEvent *e) +{ + if (e->Key == 'h' && !e->Up) { + // TODO hide the widget momentarily on the h key + return 1; + } + return 0; +} + +uiGroup *makePage7b(void) +{ + uiGroup *group; + uiBox *box; + + handler.ah.Draw = handlerDraw; + handler.ah.MouseEvent = handlerMouseEvent; + handler.ah.MouseCrossed = handlerMouseCrossed; + handler.ah.DragBroken = handlerDragBroken; + handler.ah.KeyEvent = handlerKeyEvent; + + group = newGroup("Scrolling Mouse Test"); + + box = newVerticalBox(); + uiGroupSetChild(group, uiControl(box)); + + area = uiNewScrollingArea((uiAreaHandler *) (&handler), 5000, 5000); + uiBoxAppend(box, uiControl(area), 1); + + label = uiNewCheckbox(""); + uiBoxAppend(box, uiControl(label), 0); + + return group; +} diff --git a/dep/libui/test/page7c.c b/dep/libui/test/page7c.c new file mode 100644 index 0000000..ac6a316 --- /dev/null +++ b/dep/libui/test/page7c.c @@ -0,0 +1,133 @@ +// 13 october 2015 +#include "test.h" + +static uiArea *area; + +struct handler { + uiAreaHandler ah; +}; + +static struct handler handler; + +#define areaSize 250 +#define borderThickness 1 +#define padding 30 +#define circleRadius ((areaSize - padding) / 2) + +static void handlerDraw(uiAreaHandler *a, uiArea *area, uiAreaDrawParams *dp) +{ + uiDrawPath *path; + uiDrawBrush brush; + uiDrawStrokeParams sp; + uiDrawBrushGradientStop stops[2]; + + memset(&brush, 0, sizeof (uiDrawBrush)); + memset(&sp, 0, sizeof (uiDrawStrokeParams)); + + // add some buffering to detect scrolls that aren't on the dot and draws that are outside the scroll area on Windows + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathAddRectangle(path, + -50, -50, + areaSize + 100, areaSize + 100); + uiDrawPathEnd(path); + brush.Type = uiDrawBrushTypeSolid; + brush.R = 0; + brush.G = 1; + brush.B = 0; + brush.A = 1; + uiDrawFill(dp->Context, path, &brush); + uiDrawFreePath(path); + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathAddRectangle(path, + 0, 0, + areaSize, areaSize); + uiDrawPathEnd(path); + brush.Type = uiDrawBrushTypeSolid; + brush.R = 1; + brush.G = 1; + brush.B = 1; + brush.A = 1; + uiDrawFill(dp->Context, path, &brush); + brush.Type = uiDrawBrushTypeSolid; + brush.R = 1; + brush.G = 0; + brush.B = 0; + brush.A = 1; + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.Thickness = 1; + sp.MiterLimit = uiDrawDefaultMiterLimit; + uiDrawStroke(dp->Context, path, &brush, &sp); + uiDrawFreePath(path); + + path = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigureWithArc(path, + areaSize / 2, areaSize / 2, + circleRadius, + 0, 2 * uiPi, + 0); + uiDrawPathEnd(path); + stops[0].Pos =0.0; + stops[0].R = 0.0; + stops[0].G = 1.0; + stops[0].B = 1.0; + stops[0].A = 1.0; + stops[1].Pos = 1.0; + stops[1].R = 0.0; + stops[1].G = 0.0; + stops[1].B = 1.0; + stops[1].A = 1.0; + brush.Type = uiDrawBrushTypeLinearGradient; + brush.X0 = areaSize / 2; + brush.Y0 = padding; + brush.X1 = areaSize / 2; + brush.Y1 = areaSize - padding; + brush.Stops = stops; + brush.NumStops = 2; + uiDrawFill(dp->Context, path, &brush); + uiDrawFreePath(path); +} + +static void handlerMouseEvent(uiAreaHandler *a, uiArea *area, uiAreaMouseEvent *e) +{ + // do nothing +} + +static void handlerMouseCrossed(uiAreaHandler *ah, uiArea *a, int left) +{ + // do nothing +} + +static void handlerDragBroken(uiAreaHandler *ah, uiArea *a) +{ + // do nothing +} + +static int handlerKeyEvent(uiAreaHandler *ah, uiArea *a, uiAreaKeyEvent *e) +{ + if (e->Key == 'h' && !e->Up) { + // TODO hide the widget momentarily on the h key + return 1; + } + return 0; +} + +uiGroup *makePage7c(void) +{ + uiGroup *group; + + handler.ah.Draw = handlerDraw; + handler.ah.MouseEvent = handlerMouseEvent; + handler.ah.MouseCrossed = handlerMouseCrossed; + handler.ah.DragBroken = handlerDragBroken; + handler.ah.KeyEvent = handlerKeyEvent; + + group = newGroup("Scrolling Drawing Test"); + + area = uiNewScrollingArea((uiAreaHandler *) (&handler), + areaSize, areaSize); + uiGroupSetChild(group, uiControl(area)); + + return group; +} diff --git a/dep/libui/test/page8.c b/dep/libui/test/page8.c new file mode 100644 index 0000000..7d85556 --- /dev/null +++ b/dep/libui/test/page8.c @@ -0,0 +1,46 @@ +// 22 december 2015 +#include "test.h" + +static void onListFonts(uiButton *b, void *data) +{ + uiDrawFontFamilies *ff; + char *this; + int i, n; + + uiMultilineEntrySetText(uiMultilineEntry(data), ""); + ff = uiDrawListFontFamilies(); + n = uiDrawFontFamiliesNumFamilies(ff); + for (i = 0; i < n; i++) { + this = uiDrawFontFamiliesFamily(ff, i); + uiMultilineEntryAppend(uiMultilineEntry(data), this); + uiMultilineEntryAppend(uiMultilineEntry(data), "\n"); + uiFreeText(this); + } + uiDrawFreeFontFamilies(ff); +} + +uiBox *makePage8(void) +{ + uiBox *page8; + uiGroup *group; + uiBox *vbox; + uiMultilineEntry *me; + uiButton *button; + + page8 = newHorizontalBox(); + + group = newGroup("Font Families"); + uiBoxAppend(page8, uiControl(group), 1); + + vbox = newVerticalBox(); + uiGroupSetChild(group, uiControl(vbox)); + + me = uiNewMultilineEntry(); + uiBoxAppend(vbox, uiControl(me), 1); + + button = uiNewButton("List Font Families"); + uiButtonOnClicked(button, onListFonts, me); + uiBoxAppend(vbox, uiControl(button), 0); + + return page8; +} diff --git a/dep/libui/test/page9.c b/dep/libui/test/page9.c new file mode 100644 index 0000000..65b2d3a --- /dev/null +++ b/dep/libui/test/page9.c @@ -0,0 +1,289 @@ +// 22 december 2015 +#include "test.h" + +static uiEntry *textString; +static uiEntry *textFont; +static uiEntry *textSize; +static uiCombobox *textWeight; +static uiCombobox *textItalic; +static uiCheckbox *textSmallCaps; +static uiCombobox *textStretch; +static uiEntry *textWidth; +static uiButton *textApply; +static uiCheckbox *addLeading; +static uiArea *textArea; +static uiAreaHandler textAreaHandler; + +static double entryDouble(uiEntry *e) +{ + char *s; + double d; + + s = uiEntryText(e); + d = atof(s); + uiFreeText(s); + return d; +} + +static void drawGuides(uiDrawContext *c, uiDrawTextFontMetrics *m) +{ + uiDrawPath *p; + uiDrawBrush b; + uiDrawStrokeParams sp; + double leading; + double y; + + leading = 0; + if (uiCheckboxChecked(addLeading)) + leading = m->Leading; + + memset(&b, 0, sizeof (uiDrawBrush)); + b.Type = uiDrawBrushTypeSolid; + memset(&sp, 0, sizeof (uiDrawStrokeParams)); + sp.Cap = uiDrawLineCapFlat; + sp.Join = uiDrawLineJoinMiter; + sp.MiterLimit = uiDrawDefaultMiterLimit; + sp.Thickness = 2; + + uiDrawSave(c); + + p = uiDrawNewPath(uiDrawFillModeWinding); + y = 10; + uiDrawPathNewFigure(p, 8, y); + y += m->Ascent; + uiDrawPathLineTo(p, 8, y); + uiDrawPathEnd(p); + b.R = 0.94; + b.G = 0.5; + b.B = 0.5; + b.A = 1.0; + uiDrawStroke(c, p, &b, &sp); + uiDrawFreePath(p); + + p = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(p, 8, y); + y += m->Descent; + uiDrawPathLineTo(p, 8, y); + uiDrawPathEnd(p); + b.R = 0.12; + b.G = 0.56; + b.B = 1.0; + b.A = 1.0; + uiDrawStroke(c, p, &b, &sp); + uiDrawFreePath(p); + + // and again for the second line + p = uiDrawNewPath(uiDrawFillModeWinding); + y += leading; + uiDrawPathNewFigure(p, 8, y); + y += m->Ascent; + uiDrawPathLineTo(p, 8, y); + uiDrawPathEnd(p); + b.R = 0.94; + b.G = 0.5; + b.B = 0.5; + b.A = 0.75; + uiDrawStroke(c, p, &b, &sp); + uiDrawFreePath(p); + + p = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathNewFigure(p, 8, y); + y += m->Descent; + uiDrawPathLineTo(p, 8, y); + uiDrawPathEnd(p); + b.R = 0.12; + b.G = 0.56; + b.B = 1.0; + b.A = 0.75; + uiDrawStroke(c, p, &b, &sp); + uiDrawFreePath(p); + + // and a box to text layout top-left corners + p = uiDrawNewPath(uiDrawFillModeWinding); + uiDrawPathAddRectangle(p, 0, 0, 10, 10); + uiDrawPathEnd(p); + uiDrawClip(c, p); + b.R = 0.85; + b.G = 0.65; + b.B = 0.13; + b.A = 1.0; + uiDrawStroke(c, p, &b, &sp); + uiDrawFreePath(p); + + uiDrawRestore(c); +} + +static void handlerDraw(uiAreaHandler *a, uiArea *area, uiAreaDrawParams *dp) +{ + uiDrawTextFontDescriptor desc; + uiDrawTextFont *font; + char *s; + char *family; // make compiler happy + uiDrawTextLayout *layout; + uiDrawTextFontMetrics metrics; + double ypos; + double width; + double height; + + memset(&desc, 0, sizeof (uiDrawTextFontDescriptor)); + family = uiEntryText(textFont); + desc.Family = family; + desc.Size = entryDouble(textSize); + desc.Weight = uiComboboxSelected(textWeight); + desc.Italic = uiComboboxSelected(textItalic); + desc.Stretch = uiComboboxSelected(textStretch); + font = uiDrawLoadClosestFont(&desc); + uiFreeText(family); + uiDrawTextFontGetMetrics(font, &metrics); + + width = entryDouble(textWidth); + + drawGuides(dp->Context, &metrics); + + s = uiEntryText(textString); + layout = uiDrawNewTextLayout(s, font, width); + uiFreeText(s); + if (uiCheckboxChecked(textSmallCaps)) + ; // TODO + ypos = 10; + uiDrawText(dp->Context, 10, ypos, layout); + // TODO make these optional? + uiDrawTextLayoutExtents(layout, &width, &height); + uiDrawFreeTextLayout(layout); + + layout = uiDrawNewTextLayout("This is a second line", font, -1); + if (/*TODO reuse width*/entryDouble(textWidth) < 0) { + double ad; + + ad = metrics.Ascent + metrics.Descent; + printf("ad:%g extent:%g\n", ad, height); + } + ypos += height; + if (uiCheckboxChecked(addLeading)) + ypos += metrics.Leading; + uiDrawText(dp->Context, 10, ypos, layout); + uiDrawFreeTextLayout(layout); + + uiDrawFreeTextFont(font); +} + +static void handlerMouseEvent(uiAreaHandler *a, uiArea *area, uiAreaMouseEvent *e) +{ + // do nothing +} + +static void handlerMouseCrossed(uiAreaHandler *ah, uiArea *a, int left) +{ + // do nothing +} + +static void handlerDragBroken(uiAreaHandler *ah, uiArea *a) +{ + // do nothing +} + +static int handlerKeyEvent(uiAreaHandler *ah, uiArea *a, uiAreaKeyEvent *e) +{ + // do nothing + return 0; +} + +static void onTextApply(uiButton *b, void *data) +{ + uiAreaQueueRedrawAll(textArea); +} + +uiBox *makePage9(void) +{ + uiBox *page9; + uiBox *vbox; + uiBox *hbox; + + page9 = newVerticalBox(); + vbox = page9; + + hbox = newHorizontalBox(); + uiBoxAppend(vbox, uiControl(hbox), 0); + + textString = uiNewEntry(); + // TODO make it placeholder + uiEntrySetText(textString, "Enter text here"); + uiBoxAppend(hbox, uiControl(textString), 1); + + textFont = uiNewEntry(); + uiEntrySetText(textFont, "Arial"); + uiBoxAppend(hbox, uiControl(textFont), 1); + + textSize = uiNewEntry(); + uiEntrySetText(textSize, "10"); + uiBoxAppend(hbox, uiControl(textSize), 1); + + hbox = newHorizontalBox(); + uiBoxAppend(vbox, uiControl(hbox), 0); + + textWeight = uiNewCombobox(); + uiComboboxAppend(textWeight, "Thin"); + uiComboboxAppend(textWeight, "Ultra Light"); + uiComboboxAppend(textWeight, "Light"); + uiComboboxAppend(textWeight, "Book"); + uiComboboxAppend(textWeight, "Normal"); + uiComboboxAppend(textWeight, "Medium"); + uiComboboxAppend(textWeight, "Semi Bold"); + uiComboboxAppend(textWeight, "Bold"); + uiComboboxAppend(textWeight, "Ultra Bold"); + uiComboboxAppend(textWeight, "Heavy"); + uiComboboxAppend(textWeight, "Ultra Heavy"); + uiComboboxSetSelected(textWeight, uiDrawTextWeightNormal); + uiBoxAppend(hbox, uiControl(textWeight), 1); + + textItalic = uiNewCombobox(); + uiComboboxAppend(textItalic, "Normal"); + uiComboboxAppend(textItalic, "Oblique"); + uiComboboxAppend(textItalic, "Italic"); + uiComboboxSetSelected(textItalic, uiDrawTextItalicNormal); + uiBoxAppend(hbox, uiControl(textItalic), 1); + + textSmallCaps = uiNewCheckbox("Small Caps"); + uiBoxAppend(hbox, uiControl(textSmallCaps), 1); + + hbox = newHorizontalBox(); + uiBoxAppend(vbox, uiControl(hbox), 0); + + textStretch = uiNewCombobox(); + uiComboboxAppend(textStretch, "Ultra Condensed"); + uiComboboxAppend(textStretch, "Extra Condensed"); + uiComboboxAppend(textStretch, "Condensed"); + uiComboboxAppend(textStretch, "Semi Condensed"); + uiComboboxAppend(textStretch, "Normal"); + uiComboboxAppend(textStretch, "Semi Expanded"); + uiComboboxAppend(textStretch, "Expanded"); + uiComboboxAppend(textStretch, "Extra Expanded"); + uiComboboxAppend(textStretch, "Ultra Expanded"); + uiComboboxSetSelected(textStretch, uiDrawTextStretchNormal); + uiBoxAppend(hbox, uiControl(textStretch), 1); + + textWidth = uiNewEntry(); + uiEntrySetText(textWidth, "-1"); + uiBoxAppend(hbox, uiControl(textWidth), 1); + + hbox = newHorizontalBox(); + uiBoxAppend(vbox, uiControl(hbox), 0); + + textApply = uiNewButton("Apply"); + uiButtonOnClicked(textApply, onTextApply, NULL); + uiBoxAppend(hbox, uiControl(textApply), 1); + + addLeading = uiNewCheckbox("Add Leading"); + uiCheckboxSetChecked(addLeading, 1); + uiBoxAppend(hbox, uiControl(addLeading), 0); + + textAreaHandler.Draw = handlerDraw; + textAreaHandler.MouseEvent = handlerMouseEvent; + textAreaHandler.MouseCrossed = handlerMouseCrossed; + textAreaHandler.DragBroken = handlerDragBroken; + textAreaHandler.KeyEvent = handlerKeyEvent; + textArea = uiNewArea(&textAreaHandler); + uiBoxAppend(vbox, uiControl(textArea), 1); + + return page9; +} diff --git a/dep/libui/test/resources.rc b/dep/libui/test/resources.rc new file mode 100644 index 0000000..ebc5d6e --- /dev/null +++ b/dep/libui/test/resources.rc @@ -0,0 +1,13 @@ +// 30 may 2015 + +// this is a UTF-8 file +#pragma code_page(65001) + +// this is the Common Controls 6 manifest +// TODO set up the string values here +// 1 is the value of CREATEPROCESS_MANIFEST_RESOURCE_ID and 24 is the value of RT_MANIFEST; we use it directly to avoid needing to share winapi.h with the tests and examples +#ifndef _UI_STATIC +1 24 "test.manifest" +#else +1 24 "test.static.manifest" +#endif diff --git a/dep/libui/test/spaced.c b/dep/libui/test/spaced.c new file mode 100644 index 0000000..02db99a --- /dev/null +++ b/dep/libui/test/spaced.c @@ -0,0 +1,177 @@ +// 22 april 2015 +#include "test.h" + +struct thing { + void *ptr; + int type; +}; + +static struct thing *things = NULL; +static size_t len = 0; +static size_t cap = 0; + +#define grow 32 + +static void *append(void *thing, int type) +{ + if (len >= cap) { + cap += grow; + things = (struct thing *) realloc(things, cap * sizeof (struct thing)); + if (things == NULL) + die("reallocating things array in test/spaced.c append()"); + } + things[len].ptr = thing; + things[len].type = type; + len++; + return things[len - 1].ptr; +} + +enum types { + window, + box, + tab, + group, + form, + grid, +}; + +void setSpaced(int spaced) +{ + size_t i; + void *p; + size_t j, n; + + for (i = 0; i < len; i++) { + p = things[i].ptr; + switch (things[i].type) { + case window: + uiWindowSetMargined(uiWindow(p), spaced); + break; + case box: + uiBoxSetPadded(uiBox(p), spaced); + break; + case tab: + n = uiTabNumPages(uiTab(p)); + for (j = 0; j < n; j++) + uiTabSetMargined(uiTab(p), j, spaced); + break; + case group: + uiGroupSetMargined(uiGroup(p), spaced); + break; + case form: + uiFormSetPadded(uiForm(p), spaced); + break; + case grid: + uiGridSetPadded(uiGrid(p), spaced); + break; + } + } +} + +void querySpaced(char out[12]) // more than enough +{ + int m = 0; + int p = 0; + size_t i; + void *pp; + size_t j, n; + + for (i = 0; i < len; i++) { + pp = things[i].ptr; + switch (things[i].type) { + case window: + if (uiWindowMargined(uiWindow(pp))) + m++; + break; + case box: + p = uiBoxPadded(uiBox(pp)); + break; + case tab: + n = uiTabNumPages(uiTab(pp)); + for (j = 0; j < n; j++) + if (uiTabMargined(uiTab(pp), j)) + m++; + break; + case group: + if (uiGroupMargined(uiGroup(pp))) + m++; + break; + // TODO form + // TODO grid + } + } + + out[0] = 'm'; + out[1] = ' '; + out[2] = '0' + m; + out[3] = ' '; + out[4] = 'p'; + out[5] = ' '; + out[6] = '0'; + if (p) + out[6] = '1'; + out[7] = '\0'; +} + +uiWindow *newWindow(const char *title, int width, int height, int hasMenubar) +{ + uiWindow *w; + + w = uiNewWindow(title, width, height, hasMenubar); + append(w, window); + return w; +} + +uiBox *newHorizontalBox(void) +{ + uiBox *b; + + b = (*newhbox)(); + append(b, box); + return b; +} + +uiBox *newVerticalBox(void) +{ + uiBox *b; + + b = (*newvbox)(); + append(b, box); + return b; +} + +uiTab *newTab(void) +{ + uiTab *t; + + t = uiNewTab(); + append(t, tab); + return t; +} + +uiGroup *newGroup(const char *text) +{ + uiGroup *g; + + g = uiNewGroup(text); + append(g, group); + return g; +} + +uiForm *newForm(void) +{ + uiForm *f; + + f = uiNewForm(); + append(f, form); + return f; +} + +uiGrid *newGrid(void) +{ + uiGrid *g; + + g = uiNewGrid(); + append(g, grid); + return g; +} diff --git a/dep/libui/test/test.h b/dep/libui/test/test.h new file mode 100644 index 0000000..42ec931 --- /dev/null +++ b/dep/libui/test/test.h @@ -0,0 +1,98 @@ +// 22 april 2015 +#include +#include +#include +#include +#include +#include +#include +#include "../ui.h" + +// main.c +extern void die(const char *, ...); +extern uiBox *mainBox; +extern uiTab *mainTab; +extern uiBox *(*newhbox)(void); +extern uiBox *(*newvbox)(void); + +// spaced.c +extern void setSpaced(int); +extern void querySpaced(char[12]); +extern uiWindow *newWindow(const char *title, int width, int height, int hasMenubar); +extern uiBox *newHorizontalBox(void); +extern uiBox *newVerticalBox(void); +extern uiTab *newTab(void); +extern uiGroup *newGroup(const char *); +extern uiForm *newForm(void); +extern uiGrid *newGrid(void); + +// menus.c +extern uiMenuItem *shouldQuitItem; +extern void initMenus(void); + +// page1.c +extern uiBox *page1; +extern void makePage1(uiWindow *); + +// page2.c +extern uiGroup *page2group; +extern uiBox *makePage2(void); + +// page3.c +extern uiBox *makePage3(void); + +// page4.c +extern uiBox *makePage4(void); + +// page5.c +extern uiBox *makePage5(uiWindow *); + +// page6.c +extern uiBox *makePage6(void); + +// drawtests.c +extern void runDrawTest(int, uiAreaDrawParams *); +extern void populateComboboxWithTests(uiCombobox *); + +// page7.c +extern uiBox *makePage7(void); + +// page7a.c +extern uiGroup *makePage7a(void); + +// page7b.c +extern uiGroup *makePage7b(void); + +// page7c.c +extern uiGroup *makePage7c(void); + +// page8.c +extern uiBox *makePage8(void); + +// page9.c +extern uiBox *makePage9(void); + +// page10.c +extern uiBox *makePage10(void); + +// page11.c +extern uiBox *makePage11(void); + +// page12.c +extern uiBox *makePage12(void); + +// page13.c +extern uiBox *makePage13(void); + +// page14.c +extern uiTab *makePage14(void); + +// page15.c +extern uiBox *makePage15(uiWindow *); + +// page16.c +extern uiBox *makePage16(void); +extern void freePage16(void); + +// images.c +extern void appendImageNamed(uiImage *img, const char *name); diff --git a/dep/libui/test/test.manifest b/dep/libui/test/test.manifest new file mode 100644 index 0000000..41e7c9c --- /dev/null +++ b/dep/libui/test/test.manifest @@ -0,0 +1,20 @@ + + + +Your application description here. + + + + + + + + + + + diff --git a/dep/libui/test/test.static.manifest b/dep/libui/test/test.static.manifest new file mode 100644 index 0000000..d8e83a8 --- /dev/null +++ b/dep/libui/test/test.static.manifest @@ -0,0 +1,32 @@ + + + +Your application description here. + + + + + + + + + + + + + + + + diff --git a/dep/libui/ui.h b/dep/libui/ui.h new file mode 100644 index 0000000..40aea94 --- /dev/null +++ b/dep/libui/ui.h @@ -0,0 +1,1465 @@ +// 6 april 2015 + +// TODO add a uiVerifyControlType() function that can be used by control implementations to verify controls + +// TODOs +// - make getters that return whether something exists accept a NULL pointer to discard the value (and thus only return that the thing exists?) +// - const-correct everything +// - normalize documentation between typedefs and structs + +#ifndef __LIBUI_UI_H__ +#define __LIBUI_UI_H__ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// this macro is generated by cmake +#ifdef libui_EXPORTS +#ifdef _WIN32 +#define _UI_EXTERN __declspec(dllexport) extern +#else +#define _UI_EXTERN __attribute__((visibility("default"))) extern +#endif +#else +// TODO add __declspec(dllimport) on windows, but only if not static +#define _UI_EXTERN extern +#endif + +// C++ is really really really really really really dumb about enums, so screw that and just make them anonymous +// This has the advantage of being ABI-able should we ever need an ABI... +#define _UI_ENUM(s) typedef unsigned int s; enum + +// This constant is provided because M_PI is nonstandard. +// This comes from Go's math.Pi, which in turn comes from http://oeis.org/A000796. +#define uiPi 3.14159265358979323846264338327950288419716939937510582097494459 + +// TODO uiBool? + +// uiForEach represents the return value from one of libui's various ForEach functions. +_UI_ENUM(uiForEach) { + uiForEachContinue, + uiForEachStop, +}; + +typedef struct uiInitOptions uiInitOptions; + +struct uiInitOptions { + size_t Size; +}; + +_UI_EXTERN const char *uiInit(uiInitOptions *options); +_UI_EXTERN void uiUninit(void); +_UI_EXTERN void uiFreeInitError(const char *err); + +_UI_EXTERN void uiMain(void); +_UI_EXTERN void uiMainSteps(void); +_UI_EXTERN int uiMainStep(int wait); +_UI_EXTERN void uiQuit(void); + +_UI_EXTERN void uiQueueMain(void (*f)(void *data), void *data); + +// TODO standardize the looping behavior return type, either with some enum or something, and the test expressions throughout the code +// TODO figure out what to do about looping and the exact point that the timer is rescheduled so we can document it; see https://github.com/andlabs/libui/pull/277 +// TODO (also in the above link) document that this cannot be called from any thread, unlike uiQueueMain() +// TODO document that the minimum exact timing, either accuracy (timer burst, etc.) or granularity (15ms on Windows, etc.), is OS-defined +// TODO also figure out how long until the initial tick is registered on all platforms to document +// TODO also add a comment about how useful this could be in bindings, depending on the language being bound to +_UI_EXTERN void uiTimer(int milliseconds, int (*f)(void *data), void *data); + +_UI_EXTERN void uiOnShouldQuit(int (*f)(void *data), void *data); + +_UI_EXTERN void uiFreeText(char *text); + +typedef struct uiControl uiControl; + +struct uiControl { + uint32_t Signature; + uint32_t OSSignature; + uint32_t TypeSignature; + void (*Destroy)(uiControl *); + uintptr_t (*Handle)(uiControl *); + uiControl *(*Parent)(uiControl *); + void (*SetParent)(uiControl *, uiControl *); + int (*Toplevel)(uiControl *); + int (*Visible)(uiControl *); + void (*Show)(uiControl *); + void (*Hide)(uiControl *); + int (*Enabled)(uiControl *); + void (*Enable)(uiControl *); + void (*Disable)(uiControl *); +}; +// TOOD add argument names to all arguments +#define uiControl(this) ((uiControl *) (this)) +_UI_EXTERN void uiControlDestroy(uiControl *); +_UI_EXTERN uintptr_t uiControlHandle(uiControl *); +_UI_EXTERN uiControl *uiControlParent(uiControl *); +_UI_EXTERN void uiControlSetParent(uiControl *, uiControl *); +_UI_EXTERN int uiControlToplevel(uiControl *); +_UI_EXTERN int uiControlVisible(uiControl *); +_UI_EXTERN void uiControlShow(uiControl *); +_UI_EXTERN void uiControlHide(uiControl *); +_UI_EXTERN int uiControlEnabled(uiControl *); +_UI_EXTERN void uiControlEnable(uiControl *); +_UI_EXTERN void uiControlDisable(uiControl *); + +_UI_EXTERN uiControl *uiAllocControl(size_t n, uint32_t OSsig, uint32_t typesig, const char *typenamestr); +_UI_EXTERN void uiFreeControl(uiControl *); + +// TODO make sure all controls have these +_UI_EXTERN void uiControlVerifySetParent(uiControl *, uiControl *); +_UI_EXTERN int uiControlEnabledToUser(uiControl *); + +_UI_EXTERN void uiUserBugCannotSetParentOnToplevel(const char *type); + +typedef struct uiWindow uiWindow; +#define uiWindow(this) ((uiWindow *) (this)) +_UI_EXTERN char *uiWindowTitle(uiWindow *w); +_UI_EXTERN void uiWindowSetTitle(uiWindow *w, const char *title); +_UI_EXTERN void uiWindowContentSize(uiWindow *w, int *width, int *height); +_UI_EXTERN void uiWindowSetContentSize(uiWindow *w, int width, int height); +_UI_EXTERN int uiWindowFullscreen(uiWindow *w); +_UI_EXTERN void uiWindowSetFullscreen(uiWindow *w, int fullscreen); +_UI_EXTERN void uiWindowOnContentSizeChanged(uiWindow *w, void (*f)(uiWindow *, void *), void *data); +_UI_EXTERN void uiWindowOnClosing(uiWindow *w, int (*f)(uiWindow *w, void *data), void *data); +_UI_EXTERN int uiWindowBorderless(uiWindow *w); +_UI_EXTERN void uiWindowSetBorderless(uiWindow *w, int borderless); +_UI_EXTERN void uiWindowSetChild(uiWindow *w, uiControl *child); +_UI_EXTERN int uiWindowMargined(uiWindow *w); +_UI_EXTERN void uiWindowSetMargined(uiWindow *w, int margined); +_UI_EXTERN uiWindow *uiNewWindow(const char *title, int width, int height, int hasMenubar); + +typedef struct uiButton uiButton; +#define uiButton(this) ((uiButton *) (this)) +_UI_EXTERN char *uiButtonText(uiButton *b); +_UI_EXTERN void uiButtonSetText(uiButton *b, const char *text); +_UI_EXTERN void uiButtonOnClicked(uiButton *b, void (*f)(uiButton *b, void *data), void *data); +_UI_EXTERN uiButton *uiNewButton(const char *text); + +typedef struct uiBox uiBox; +#define uiBox(this) ((uiBox *) (this)) +_UI_EXTERN void uiBoxAppend(uiBox *b, uiControl *child, int stretchy); +_UI_EXTERN void uiBoxDelete(uiBox *b, int index); +_UI_EXTERN int uiBoxPadded(uiBox *b); +_UI_EXTERN void uiBoxSetPadded(uiBox *b, int padded); +_UI_EXTERN uiBox *uiNewHorizontalBox(void); +_UI_EXTERN uiBox *uiNewVerticalBox(void); + +typedef struct uiCheckbox uiCheckbox; +#define uiCheckbox(this) ((uiCheckbox *) (this)) +_UI_EXTERN char *uiCheckboxText(uiCheckbox *c); +_UI_EXTERN void uiCheckboxSetText(uiCheckbox *c, const char *text); +_UI_EXTERN void uiCheckboxOnToggled(uiCheckbox *c, void (*f)(uiCheckbox *c, void *data), void *data); +_UI_EXTERN int uiCheckboxChecked(uiCheckbox *c); +_UI_EXTERN void uiCheckboxSetChecked(uiCheckbox *c, int checked); +_UI_EXTERN uiCheckbox *uiNewCheckbox(const char *text); + +typedef struct uiEntry uiEntry; +#define uiEntry(this) ((uiEntry *) (this)) +_UI_EXTERN char *uiEntryText(uiEntry *e); +_UI_EXTERN void uiEntrySetText(uiEntry *e, const char *text); +_UI_EXTERN void uiEntryOnChanged(uiEntry *e, void (*f)(uiEntry *e, void *data), void *data); +_UI_EXTERN int uiEntryReadOnly(uiEntry *e); +_UI_EXTERN void uiEntrySetReadOnly(uiEntry *e, int readonly); +_UI_EXTERN uiEntry *uiNewEntry(void); +_UI_EXTERN uiEntry *uiNewPasswordEntry(void); +_UI_EXTERN uiEntry *uiNewSearchEntry(void); + +typedef struct uiLabel uiLabel; +#define uiLabel(this) ((uiLabel *) (this)) +_UI_EXTERN char *uiLabelText(uiLabel *l); +_UI_EXTERN void uiLabelSetText(uiLabel *l, const char *text); +_UI_EXTERN uiLabel *uiNewLabel(const char *text); + +typedef struct uiTab uiTab; +#define uiTab(this) ((uiTab *) (this)) +_UI_EXTERN void uiTabAppend(uiTab *t, const char *name, uiControl *c); +_UI_EXTERN void uiTabInsertAt(uiTab *t, const char *name, int before, uiControl *c); +_UI_EXTERN void uiTabDelete(uiTab *t, int index); +_UI_EXTERN int uiTabNumPages(uiTab *t); +_UI_EXTERN int uiTabMargined(uiTab *t, int page); +_UI_EXTERN void uiTabSetMargined(uiTab *t, int page, int margined); +_UI_EXTERN uiTab *uiNewTab(void); + +typedef struct uiGroup uiGroup; +#define uiGroup(this) ((uiGroup *) (this)) +_UI_EXTERN char *uiGroupTitle(uiGroup *g); +_UI_EXTERN void uiGroupSetTitle(uiGroup *g, const char *title); +_UI_EXTERN void uiGroupSetChild(uiGroup *g, uiControl *c); +_UI_EXTERN int uiGroupMargined(uiGroup *g); +_UI_EXTERN void uiGroupSetMargined(uiGroup *g, int margined); +_UI_EXTERN uiGroup *uiNewGroup(const char *title); + +// spinbox/slider rules: +// setting value outside of range will automatically clamp +// initial value is minimum +// complaint if min >= max? + +typedef struct uiSpinbox uiSpinbox; +#define uiSpinbox(this) ((uiSpinbox *) (this)) +_UI_EXTERN int uiSpinboxValue(uiSpinbox *s); +_UI_EXTERN void uiSpinboxSetValue(uiSpinbox *s, int value); +_UI_EXTERN void uiSpinboxOnChanged(uiSpinbox *s, void (*f)(uiSpinbox *s, void *data), void *data); +_UI_EXTERN uiSpinbox *uiNewSpinbox(int min, int max); + +typedef struct uiSlider uiSlider; +#define uiSlider(this) ((uiSlider *) (this)) +_UI_EXTERN int uiSliderValue(uiSlider *s); +_UI_EXTERN void uiSliderSetValue(uiSlider *s, int value); +_UI_EXTERN void uiSliderOnChanged(uiSlider *s, void (*f)(uiSlider *s, void *data), void *data); +_UI_EXTERN uiSlider *uiNewSlider(int min, int max); + +typedef struct uiProgressBar uiProgressBar; +#define uiProgressBar(this) ((uiProgressBar *) (this)) +_UI_EXTERN int uiProgressBarValue(uiProgressBar *p); +_UI_EXTERN void uiProgressBarSetValue(uiProgressBar *p, int n); +_UI_EXTERN uiProgressBar *uiNewProgressBar(void); + +typedef struct uiSeparator uiSeparator; +#define uiSeparator(this) ((uiSeparator *) (this)) +_UI_EXTERN uiSeparator *uiNewHorizontalSeparator(void); +_UI_EXTERN uiSeparator *uiNewVerticalSeparator(void); + +typedef struct uiCombobox uiCombobox; +#define uiCombobox(this) ((uiCombobox *) (this)) +_UI_EXTERN void uiComboboxAppend(uiCombobox *c, const char *text); +_UI_EXTERN int uiComboboxSelected(uiCombobox *c); +_UI_EXTERN void uiComboboxSetSelected(uiCombobox *c, int n); +_UI_EXTERN void uiComboboxOnSelected(uiCombobox *c, void (*f)(uiCombobox *c, void *data), void *data); +_UI_EXTERN uiCombobox *uiNewCombobox(void); + +typedef struct uiEditableCombobox uiEditableCombobox; +#define uiEditableCombobox(this) ((uiEditableCombobox *) (this)) +_UI_EXTERN void uiEditableComboboxAppend(uiEditableCombobox *c, const char *text); +_UI_EXTERN char *uiEditableComboboxText(uiEditableCombobox *c); +_UI_EXTERN void uiEditableComboboxSetText(uiEditableCombobox *c, const char *text); +// TODO what do we call a function that sets the currently selected item and fills the text field with it? editable comboboxes have no consistent concept of selected item +_UI_EXTERN void uiEditableComboboxOnChanged(uiEditableCombobox *c, void (*f)(uiEditableCombobox *c, void *data), void *data); +_UI_EXTERN uiEditableCombobox *uiNewEditableCombobox(void); + +typedef struct uiRadioButtons uiRadioButtons; +#define uiRadioButtons(this) ((uiRadioButtons *) (this)) +_UI_EXTERN void uiRadioButtonsAppend(uiRadioButtons *r, const char *text); +_UI_EXTERN int uiRadioButtonsSelected(uiRadioButtons *r); +_UI_EXTERN void uiRadioButtonsSetSelected(uiRadioButtons *r, int n); +_UI_EXTERN void uiRadioButtonsOnSelected(uiRadioButtons *r, void (*f)(uiRadioButtons *, void *), void *data); +_UI_EXTERN uiRadioButtons *uiNewRadioButtons(void); + +struct tm; +typedef struct uiDateTimePicker uiDateTimePicker; +#define uiDateTimePicker(this) ((uiDateTimePicker *) (this)) +// TODO document that tm_wday and tm_yday are undefined, and tm_isdst should be -1 +// TODO document that for both sides +// TODO document time zone conversions or lack thereof +// TODO for Time: define what values are returned when a part is missing +_UI_EXTERN void uiDateTimePickerTime(uiDateTimePicker *d, struct tm *time); +_UI_EXTERN void uiDateTimePickerSetTime(uiDateTimePicker *d, const struct tm *time); +_UI_EXTERN void uiDateTimePickerOnChanged(uiDateTimePicker *d, void (*f)(uiDateTimePicker *, void *), void *data); +_UI_EXTERN uiDateTimePicker *uiNewDateTimePicker(void); +_UI_EXTERN uiDateTimePicker *uiNewDatePicker(void); +_UI_EXTERN uiDateTimePicker *uiNewTimePicker(void); + +// TODO provide a facility for entering tab stops? +typedef struct uiMultilineEntry uiMultilineEntry; +#define uiMultilineEntry(this) ((uiMultilineEntry *) (this)) +_UI_EXTERN char *uiMultilineEntryText(uiMultilineEntry *e); +_UI_EXTERN void uiMultilineEntrySetText(uiMultilineEntry *e, const char *text); +_UI_EXTERN void uiMultilineEntryAppend(uiMultilineEntry *e, const char *text); +_UI_EXTERN void uiMultilineEntryOnChanged(uiMultilineEntry *e, void (*f)(uiMultilineEntry *e, void *data), void *data); +_UI_EXTERN int uiMultilineEntryReadOnly(uiMultilineEntry *e); +_UI_EXTERN void uiMultilineEntrySetReadOnly(uiMultilineEntry *e, int readonly); +_UI_EXTERN uiMultilineEntry *uiNewMultilineEntry(void); +_UI_EXTERN uiMultilineEntry *uiNewNonWrappingMultilineEntry(void); + +typedef struct uiMenuItem uiMenuItem; +#define uiMenuItem(this) ((uiMenuItem *) (this)) +_UI_EXTERN void uiMenuItemEnable(uiMenuItem *m); +_UI_EXTERN void uiMenuItemDisable(uiMenuItem *m); +_UI_EXTERN void uiMenuItemOnClicked(uiMenuItem *m, void (*f)(uiMenuItem *sender, uiWindow *window, void *data), void *data); +_UI_EXTERN int uiMenuItemChecked(uiMenuItem *m); +_UI_EXTERN void uiMenuItemSetChecked(uiMenuItem *m, int checked); + +typedef struct uiMenu uiMenu; +#define uiMenu(this) ((uiMenu *) (this)) +_UI_EXTERN uiMenuItem *uiMenuAppendItem(uiMenu *m, const char *name); +_UI_EXTERN uiMenuItem *uiMenuAppendCheckItem(uiMenu *m, const char *name); +_UI_EXTERN uiMenuItem *uiMenuAppendQuitItem(uiMenu *m); +_UI_EXTERN uiMenuItem *uiMenuAppendPreferencesItem(uiMenu *m); +_UI_EXTERN uiMenuItem *uiMenuAppendAboutItem(uiMenu *m); +_UI_EXTERN void uiMenuAppendSeparator(uiMenu *m); +_UI_EXTERN uiMenu *uiNewMenu(const char *name); + +_UI_EXTERN char *uiOpenFile(uiWindow *parent); +_UI_EXTERN char *uiSaveFile(uiWindow *parent); +_UI_EXTERN void uiMsgBox(uiWindow *parent, const char *title, const char *description); +_UI_EXTERN void uiMsgBoxError(uiWindow *parent, const char *title, const char *description); + +typedef struct uiArea uiArea; +typedef struct uiAreaHandler uiAreaHandler; +typedef struct uiAreaDrawParams uiAreaDrawParams; +typedef struct uiAreaMouseEvent uiAreaMouseEvent; +typedef struct uiAreaKeyEvent uiAreaKeyEvent; + +typedef struct uiDrawContext uiDrawContext; + +struct uiAreaHandler { + void (*Draw)(uiAreaHandler *, uiArea *, uiAreaDrawParams *); + // TODO document that resizes cause a full redraw for non-scrolling areas; implementation-defined for scrolling areas + void (*MouseEvent)(uiAreaHandler *, uiArea *, uiAreaMouseEvent *); + // TODO document that on first show if the mouse is already in the uiArea then one gets sent with left=0 + // TODO what about when the area is hidden and then shown again? + void (*MouseCrossed)(uiAreaHandler *, uiArea *, int left); + void (*DragBroken)(uiAreaHandler *, uiArea *); + int (*KeyEvent)(uiAreaHandler *, uiArea *, uiAreaKeyEvent *); +}; + +// TODO RTL layouts? +// TODO reconcile edge and corner naming +_UI_ENUM(uiWindowResizeEdge) { + uiWindowResizeEdgeLeft, + uiWindowResizeEdgeTop, + uiWindowResizeEdgeRight, + uiWindowResizeEdgeBottom, + uiWindowResizeEdgeTopLeft, + uiWindowResizeEdgeTopRight, + uiWindowResizeEdgeBottomLeft, + uiWindowResizeEdgeBottomRight, + // TODO have one for keyboard resizes? + // TODO GDK doesn't seem to have any others, including for keyboards... + // TODO way to bring up the system menu instead? +}; + +#define uiArea(this) ((uiArea *) (this)) +// TODO give a better name +// TODO document the types of width and height +_UI_EXTERN void uiAreaSetSize(uiArea *a, int width, int height); +// TODO uiAreaQueueRedraw() +_UI_EXTERN void uiAreaQueueRedrawAll(uiArea *a); +_UI_EXTERN void uiAreaScrollTo(uiArea *a, double x, double y, double width, double height); +// TODO document these can only be called within Mouse() handlers +// TODO should these be allowed on scrolling areas? +// TODO decide which mouse events should be accepted; Down is the only one guaranteed to work right now +// TODO what happens to events after calling this up to and including the next mouse up? +// TODO release capture? +_UI_EXTERN void uiAreaBeginUserWindowMove(uiArea *a); +_UI_EXTERN void uiAreaBeginUserWindowResize(uiArea *a, uiWindowResizeEdge edge); +_UI_EXTERN uiArea *uiNewArea(uiAreaHandler *ah); +_UI_EXTERN uiArea *uiNewScrollingArea(uiAreaHandler *ah, int width, int height); + +struct uiAreaDrawParams { + uiDrawContext *Context; + + // TODO document that this is only defined for nonscrolling areas + double AreaWidth; + double AreaHeight; + + double ClipX; + double ClipY; + double ClipWidth; + double ClipHeight; +}; + +typedef struct uiDrawPath uiDrawPath; +typedef struct uiDrawBrush uiDrawBrush; +typedef struct uiDrawStrokeParams uiDrawStrokeParams; +typedef struct uiDrawMatrix uiDrawMatrix; + +typedef struct uiDrawBrushGradientStop uiDrawBrushGradientStop; + +_UI_ENUM(uiDrawBrushType) { + uiDrawBrushTypeSolid, + uiDrawBrushTypeLinearGradient, + uiDrawBrushTypeRadialGradient, + uiDrawBrushTypeImage, +}; + +_UI_ENUM(uiDrawLineCap) { + uiDrawLineCapFlat, + uiDrawLineCapRound, + uiDrawLineCapSquare, +}; + +_UI_ENUM(uiDrawLineJoin) { + uiDrawLineJoinMiter, + uiDrawLineJoinRound, + uiDrawLineJoinBevel, +}; + +// this is the default for botoh cairo and Direct2D (in the latter case, from the C++ helper functions) +// Core Graphics doesn't explicitly specify a default, but NSBezierPath allows you to choose one, and this is the initial value +// so we're good to use it too! +#define uiDrawDefaultMiterLimit 10.0 + +_UI_ENUM(uiDrawFillMode) { + uiDrawFillModeWinding, + uiDrawFillModeAlternate, +}; + +struct uiDrawMatrix { + double M11; + double M12; + double M21; + double M22; + double M31; + double M32; +}; + +struct uiDrawBrush { + uiDrawBrushType Type; + + // solid brushes + double R; + double G; + double B; + double A; + + // gradient brushes + double X0; // linear: start X, radial: start X + double Y0; // linear: start Y, radial: start Y + double X1; // linear: end X, radial: outer circle center X + double Y1; // linear: end Y, radial: outer circle center Y + double OuterRadius; // radial gradients only + uiDrawBrushGradientStop *Stops; + size_t NumStops; + // TODO extend mode + // cairo: none, repeat, reflect, pad; no individual control + // Direct2D: repeat, reflect, pad; no individual control + // Core Graphics: none, pad; before and after individually + // TODO cairo documentation is inconsistent about pad + + // TODO images + + // TODO transforms +}; + +struct uiDrawBrushGradientStop { + double Pos; + double R; + double G; + double B; + double A; +}; + +struct uiDrawStrokeParams { + uiDrawLineCap Cap; + uiDrawLineJoin Join; + // TODO what if this is 0? on windows there will be a crash with dashing + double Thickness; + double MiterLimit; + double *Dashes; + // TOOD what if this is 1 on Direct2D? + // TODO what if a dash is 0 on Cairo or Quartz? + size_t NumDashes; + double DashPhase; +}; + +_UI_EXTERN uiDrawPath *uiDrawNewPath(uiDrawFillMode fillMode); +_UI_EXTERN void uiDrawFreePath(uiDrawPath *p); + +_UI_EXTERN void uiDrawPathNewFigure(uiDrawPath *p, double x, double y); +_UI_EXTERN void uiDrawPathNewFigureWithArc(uiDrawPath *p, double xCenter, double yCenter, double radius, double startAngle, double sweep, int negative); +_UI_EXTERN void uiDrawPathLineTo(uiDrawPath *p, double x, double y); +// notes: angles are both relative to 0 and go counterclockwise +// TODO is the initial line segment on cairo and OS X a proper join? +// TODO what if sweep < 0? +_UI_EXTERN void uiDrawPathArcTo(uiDrawPath *p, double xCenter, double yCenter, double radius, double startAngle, double sweep, int negative); +_UI_EXTERN void uiDrawPathBezierTo(uiDrawPath *p, double c1x, double c1y, double c2x, double c2y, double endX, double endY); +// TODO quadratic bezier +_UI_EXTERN void uiDrawPathCloseFigure(uiDrawPath *p); + +// TODO effect of these when a figure is already started +_UI_EXTERN void uiDrawPathAddRectangle(uiDrawPath *p, double x, double y, double width, double height); + +_UI_EXTERN void uiDrawPathEnd(uiDrawPath *p); + +_UI_EXTERN void uiDrawStroke(uiDrawContext *c, uiDrawPath *path, uiDrawBrush *b, uiDrawStrokeParams *p); +_UI_EXTERN void uiDrawFill(uiDrawContext *c, uiDrawPath *path, uiDrawBrush *b); + +// TODO primitives: +// - rounded rectangles +// - elliptical arcs +// - quadratic bezier curves + +_UI_EXTERN void uiDrawMatrixSetIdentity(uiDrawMatrix *m); +_UI_EXTERN void uiDrawMatrixTranslate(uiDrawMatrix *m, double x, double y); +_UI_EXTERN void uiDrawMatrixScale(uiDrawMatrix *m, double xCenter, double yCenter, double x, double y); +_UI_EXTERN void uiDrawMatrixRotate(uiDrawMatrix *m, double x, double y, double amount); +_UI_EXTERN void uiDrawMatrixSkew(uiDrawMatrix *m, double x, double y, double xamount, double yamount); +_UI_EXTERN void uiDrawMatrixMultiply(uiDrawMatrix *dest, uiDrawMatrix *src); +_UI_EXTERN int uiDrawMatrixInvertible(uiDrawMatrix *m); +_UI_EXTERN int uiDrawMatrixInvert(uiDrawMatrix *m); +_UI_EXTERN void uiDrawMatrixTransformPoint(uiDrawMatrix *m, double *x, double *y); +_UI_EXTERN void uiDrawMatrixTransformSize(uiDrawMatrix *m, double *x, double *y); + +_UI_EXTERN void uiDrawTransform(uiDrawContext *c, uiDrawMatrix *m); + +// TODO add a uiDrawPathStrokeToFill() or something like that +_UI_EXTERN void uiDrawClip(uiDrawContext *c, uiDrawPath *path); + +_UI_EXTERN void uiDrawSave(uiDrawContext *c); +_UI_EXTERN void uiDrawRestore(uiDrawContext *c); + +// uiAttribute stores information about an attribute in a +// uiAttributedString. +// +// You do not create uiAttributes directly; instead, you create a +// uiAttribute of a given type using the specialized constructor +// functions. For every Unicode codepoint in the uiAttributedString, +// at most one value of each attribute type can be applied. +// +// uiAttributes are immutable and the uiAttributedString takes +// ownership of the uiAttribute object once assigned, copying its +// contents as necessary. +typedef struct uiAttribute uiAttribute; + +// @role uiAttribute destructor +// uiFreeAttribute() frees a uiAttribute. You generally do not need to +// call this yourself, as uiAttributedString does this for you. In fact, +// it is an error to call this function on a uiAttribute that has been +// given to a uiAttributedString. You can call this, however, if you +// created a uiAttribute that you aren't going to use later. +_UI_EXTERN void uiFreeAttribute(uiAttribute *a); + +// uiAttributeType holds the possible uiAttribute types that may be +// returned by uiAttributeGetType(). Refer to the documentation for +// each type's constructor function for details on each type. +_UI_ENUM(uiAttributeType) { + uiAttributeTypeFamily, + uiAttributeTypeSize, + uiAttributeTypeWeight, + uiAttributeTypeItalic, + uiAttributeTypeStretch, + uiAttributeTypeColor, + uiAttributeTypeBackground, + uiAttributeTypeUnderline, + uiAttributeTypeUnderlineColor, + uiAttributeTypeFeatures, +}; + +// uiAttributeGetType() returns the type of a. +// TODO I don't like this name +_UI_EXTERN uiAttributeType uiAttributeGetType(const uiAttribute *a); + +// uiNewFamilyAttribute() creates a new uiAttribute that changes the +// font family of the text it is applied to. family is copied; you do not +// need to keep it alive after uiNewFamilyAttribute() returns. Font +// family names are case-insensitive. +_UI_EXTERN uiAttribute *uiNewFamilyAttribute(const char *family); + +// uiAttributeFamily() returns the font family stored in a. The +// returned string is owned by a. It is an error to call this on a +// uiAttribute that does not hold a font family. +_UI_EXTERN const char *uiAttributeFamily(const uiAttribute *a); + +// uiNewSizeAttribute() creates a new uiAttribute that changes the +// size of the text it is applied to, in typographical points. +_UI_EXTERN uiAttribute *uiNewSizeAttribute(double size); + +// uiAttributeSize() returns the font size stored in a. It is an error to +// call this on a uiAttribute that does not hold a font size. +_UI_EXTERN double uiAttributeSize(const uiAttribute *a); + +// uiTextWeight represents possible text weights. These roughly +// map to the OS/2 text weight field of TrueType and OpenType +// fonts, or to CSS weight numbers. The named constants are +// nominal values; the actual values may vary by font and by OS, +// though this isn't particularly likely. Any value between +// uiTextWeightMinimum and uiTextWeightMaximum, inclusive, +// is allowed. +// +// Note that due to restrictions in early versions of Windows, some +// fonts have "special" weights be exposed in many programs as +// separate font families. This is perhaps most notable with +// Arial Black. libui does not do this, even on Windows (because the +// DirectWrite API libui uses on Windows does not do this); to +// specify Arial Black, use family Arial and weight uiTextWeightBlack. +_UI_ENUM(uiTextWeight) { + uiTextWeightMinimum = 0, + uiTextWeightThin = 100, + uiTextWeightUltraLight = 200, + uiTextWeightLight = 300, + uiTextWeightBook = 350, + uiTextWeightNormal = 400, + uiTextWeightMedium = 500, + uiTextWeightSemiBold = 600, + uiTextWeightBold = 700, + uiTextWeightUltraBold = 800, + uiTextWeightHeavy = 900, + uiTextWeightUltraHeavy = 950, + uiTextWeightMaximum = 1000, +}; + +// uiNewWeightAttribute() creates a new uiAttribute that changes the +// weight of the text it is applied to. It is an error to specify a weight +// outside the range [uiTextWeightMinimum, +// uiTextWeightMaximum]. +_UI_EXTERN uiAttribute *uiNewWeightAttribute(uiTextWeight weight); + +// uiAttributeWeight() returns the font weight stored in a. It is an error +// to call this on a uiAttribute that does not hold a font weight. +_UI_EXTERN uiTextWeight uiAttributeWeight(const uiAttribute *a); + +// uiTextItalic represents possible italic modes for a font. Italic +// represents "true" italics where the slanted glyphs have custom +// shapes, whereas oblique represents italics that are merely slanted +// versions of the normal glyphs. Most fonts usually have one or the +// other. +_UI_ENUM(uiTextItalic) { + uiTextItalicNormal, + uiTextItalicOblique, + uiTextItalicItalic, +}; + +// uiNewItalicAttribute() creates a new uiAttribute that changes the +// italic mode of the text it is applied to. It is an error to specify an +// italic mode not specified in uiTextItalic. +_UI_EXTERN uiAttribute *uiNewItalicAttribute(uiTextItalic italic); + +// uiAttributeItalic() returns the font italic mode stored in a. It is an +// error to call this on a uiAttribute that does not hold a font italic +// mode. +_UI_EXTERN uiTextItalic uiAttributeItalic(const uiAttribute *a); + +// uiTextStretch represents possible stretches (also called "widths") +// of a font. +// +// Note that due to restrictions in early versions of Windows, some +// fonts have "special" stretches be exposed in many programs as +// separate font families. This is perhaps most notable with +// Arial Condensed. libui does not do this, even on Windows (because +// the DirectWrite API libui uses on Windows does not do this); to +// specify Arial Condensed, use family Arial and stretch +// uiTextStretchCondensed. +_UI_ENUM(uiTextStretch) { + uiTextStretchUltraCondensed, + uiTextStretchExtraCondensed, + uiTextStretchCondensed, + uiTextStretchSemiCondensed, + uiTextStretchNormal, + uiTextStretchSemiExpanded, + uiTextStretchExpanded, + uiTextStretchExtraExpanded, + uiTextStretchUltraExpanded, +}; + +// uiNewStretchAttribute() creates a new uiAttribute that changes the +// stretch of the text it is applied to. It is an error to specify a strech +// not specified in uiTextStretch. +_UI_EXTERN uiAttribute *uiNewStretchAttribute(uiTextStretch stretch); + +// uiAttributeStretch() returns the font stretch stored in a. It is an +// error to call this on a uiAttribute that does not hold a font stretch. +_UI_EXTERN uiTextStretch uiAttributeStretch(const uiAttribute *a); + +// uiNewColorAttribute() creates a new uiAttribute that changes the +// color of the text it is applied to. It is an error to specify an invalid +// color. +_UI_EXTERN uiAttribute *uiNewColorAttribute(double r, double g, double b, double a); + +// uiAttributeColor() returns the text color stored in a. It is an +// error to call this on a uiAttribute that does not hold a text color. +_UI_EXTERN void uiAttributeColor(const uiAttribute *a, double *r, double *g, double *b, double *alpha); + +// uiNewBackgroundAttribute() creates a new uiAttribute that +// changes the background color of the text it is applied to. It is an +// error to specify an invalid color. +_UI_EXTERN uiAttribute *uiNewBackgroundAttribute(double r, double g, double b, double a); + +// TODO reuse uiAttributeColor() for background colors, or make a new function... + +// uiUnderline specifies a type of underline to use on text. +_UI_ENUM(uiUnderline) { + uiUnderlineNone, + uiUnderlineSingle, + uiUnderlineDouble, + uiUnderlineSuggestion, // wavy or dotted underlines used for spelling/grammar checkers +}; + +// uiNewUnderlineAttribute() creates a new uiAttribute that changes +// the type of underline on the text it is applied to. It is an error to +// specify an underline type not specified in uiUnderline. +_UI_EXTERN uiAttribute *uiNewUnderlineAttribute(uiUnderline u); + +// uiAttributeUnderline() returns the underline type stored in a. It is +// an error to call this on a uiAttribute that does not hold an underline +// style. +_UI_EXTERN uiUnderline uiAttributeUnderline(const uiAttribute *a); + +// uiUnderlineColor specifies the color of any underline on the text it +// is applied to, regardless of the type of underline. In addition to +// being able to specify a custom color, you can explicitly specify +// platform-specific colors for suggestion underlines; to use them +// correctly, pair them with uiUnderlineSuggestion (though they can +// be used on other types of underline as well). +// +// If an underline type is applied but no underline color is +// specified, the text color is used instead. If an underline color +// is specified without an underline type, the underline color +// attribute is ignored, but not removed from the uiAttributedString. +_UI_ENUM(uiUnderlineColor) { + uiUnderlineColorCustom, + uiUnderlineColorSpelling, + uiUnderlineColorGrammar, + uiUnderlineColorAuxiliary, // for instance, the color used by smart replacements on macOS or in Microsoft Office +}; + +// uiNewUnderlineColorAttribute() creates a new uiAttribute that +// changes the color of the underline on the text it is applied to. +// It is an error to specify an underline color not specified in +// uiUnderlineColor. +// +// If the specified color type is uiUnderlineColorCustom, it is an +// error to specify an invalid color value. Otherwise, the color values +// are ignored and should be specified as zero. +_UI_EXTERN uiAttribute *uiNewUnderlineColorAttribute(uiUnderlineColor u, double r, double g, double b, double a); + +// uiAttributeUnderlineColor() returns the underline color stored in +// a. It is an error to call this on a uiAttribute that does not hold an +// underline color. +_UI_EXTERN void uiAttributeUnderlineColor(const uiAttribute *a, uiUnderlineColor *u, double *r, double *g, double *b, double *alpha); + +// uiOpenTypeFeatures represents a set of OpenType feature +// tag-value pairs, for applying OpenType features to text. +// OpenType feature tags are four-character codes defined by +// OpenType that cover things from design features like small +// caps and swashes to language-specific glyph shapes and +// beyond. Each tag may only appear once in any given +// uiOpenTypeFeatures instance. Each value is a 32-bit integer, +// often used as a Boolean flag, but sometimes as an index to choose +// a glyph shape to use. +// +// If a font does not support a certain feature, that feature will be +// ignored. (TODO verify this on all OSs) +// +// See the OpenType specification at +// https://www.microsoft.com/typography/otspec/featuretags.htm +// for the complete list of available features, information on specific +// features, and how to use them. +// TODO invalid features +typedef struct uiOpenTypeFeatures uiOpenTypeFeatures; + +// uiOpenTypeFeaturesForEachFunc is the type of the function +// invoked by uiOpenTypeFeaturesForEach() for every OpenType +// feature in otf. Refer to that function's documentation for more +// details. +typedef uiForEach (*uiOpenTypeFeaturesForEachFunc)(const uiOpenTypeFeatures *otf, char a, char b, char c, char d, uint32_t value, void *data); + +// @role uiOpenTypeFeatures constructor +// uiNewOpenTypeFeatures() returns a new uiOpenTypeFeatures +// instance, with no tags yet added. +_UI_EXTERN uiOpenTypeFeatures *uiNewOpenTypeFeatures(void); + +// @role uiOpenTypeFeatures destructor +// uiFreeOpenTypeFeatures() frees otf. +_UI_EXTERN void uiFreeOpenTypeFeatures(uiOpenTypeFeatures *otf); + +// uiOpenTypeFeaturesClone() makes a copy of otf and returns it. +// Changing one will not affect the other. +_UI_EXTERN uiOpenTypeFeatures *uiOpenTypeFeaturesClone(const uiOpenTypeFeatures *otf); + +// uiOpenTypeFeaturesAdd() adds the given feature tag and value +// to otf. The feature tag is specified by a, b, c, and d. If there is +// already a value associated with the specified tag in otf, the old +// value is removed. +_UI_EXTERN void uiOpenTypeFeaturesAdd(uiOpenTypeFeatures *otf, char a, char b, char c, char d, uint32_t value); + +// uiOpenTypeFeaturesRemove() removes the given feature tag +// and value from otf. If the tag is not present in otf, +// uiOpenTypeFeaturesRemove() does nothing. +_UI_EXTERN void uiOpenTypeFeaturesRemove(uiOpenTypeFeatures *otf, char a, char b, char c, char d); + +// uiOpenTypeFeaturesGet() determines whether the given feature +// tag is present in otf. If it is, *value is set to the tag's value and +// nonzero is returned. Otherwise, zero is returned. +// +// Note that if uiOpenTypeFeaturesGet() returns zero, value isn't +// changed. This is important: if a feature is not present in a +// uiOpenTypeFeatures, the feature is NOT treated as if its +// value was zero anyway. Script-specific font shaping rules and +// font-specific feature settings may use a different default value +// for a feature. You should likewise not treat a missing feature as +// having a value of zero either. Instead, a missing feature should +// be treated as having some unspecified default value. +_UI_EXTERN int uiOpenTypeFeaturesGet(const uiOpenTypeFeatures *otf, char a, char b, char c, char d, uint32_t *value); + +// uiOpenTypeFeaturesForEach() executes f for every tag-value +// pair in otf. The enumeration order is unspecified. You cannot +// modify otf while uiOpenTypeFeaturesForEach() is running. +_UI_EXTERN void uiOpenTypeFeaturesForEach(const uiOpenTypeFeatures *otf, uiOpenTypeFeaturesForEachFunc f, void *data); + +// uiNewFeaturesAttribute() creates a new uiAttribute that changes +// the font family of the text it is applied to. otf is copied; you may +// free it after uiNewFeaturesAttribute() returns. +_UI_EXTERN uiAttribute *uiNewFeaturesAttribute(const uiOpenTypeFeatures *otf); + +// uiAttributeFeatures() returns the OpenType features stored in a. +// The returned uiOpenTypeFeatures object is owned by a. It is an +// error to call this on a uiAttribute that does not hold OpenType +// features. +_UI_EXTERN const uiOpenTypeFeatures *uiAttributeFeatures(const uiAttribute *a); + +// uiAttributedString represents a string of UTF-8 text that can +// optionally be embellished with formatting attributes. libui +// provides the list of formatting attributes, which cover common +// formatting traits like boldface and color as well as advanced +// typographical features provided by OpenType like superscripts +// and small caps. These attributes can be combined in a variety of +// ways. +// +// Attributes are applied to runs of Unicode codepoints in the string. +// Zero-length runs are elided. Consecutive runs that have the same +// attribute type and value are merged. Each attribute is independent +// of each other attribute; overlapping attributes of different types +// do not split each other apart, but different values of the same +// attribute type do. +// +// The empty string can also be represented by uiAttributedString, +// but because of the no-zero-length-attribute rule, it will not have +// attributes. +// +// A uiAttributedString takes ownership of all attributes given to +// it, as it may need to duplicate or delete uiAttribute objects at +// any time. By extension, when you free a uiAttributedString, +// all uiAttributes within will also be freed. Each method will +// describe its own rules in more details. +// +// In addition, uiAttributedString provides facilities for moving +// between grapheme clusters, which represent a character +// from the point of view of the end user. The cursor of a text editor +// is always placed on a grapheme boundary, so you can use these +// features to move the cursor left or right by one "character". +// TODO does uiAttributedString itself need this +// +// uiAttributedString does not provide enough information to be able +// to draw itself onto a uiDrawContext or respond to user actions. +// In order to do that, you'll need to use a uiDrawTextLayout, which +// is built from the combination of a uiAttributedString and a set of +// layout-specific properties. +typedef struct uiAttributedString uiAttributedString; + +// uiAttributedStringForEachAttributeFunc is the type of the function +// invoked by uiAttributedStringForEachAttribute() for every +// attribute in s. Refer to that function's documentation for more +// details. +typedef uiForEach (*uiAttributedStringForEachAttributeFunc)(const uiAttributedString *s, const uiAttribute *a, size_t start, size_t end, void *data); + +// @role uiAttributedString constructor +// uiNewAttributedString() creates a new uiAttributedString from +// initialString. The string will be entirely unattributed. +_UI_EXTERN uiAttributedString *uiNewAttributedString(const char *initialString); + +// @role uiAttributedString destructor +// uiFreeAttributedString() destroys the uiAttributedString s. +// It will also free all uiAttributes within. +_UI_EXTERN void uiFreeAttributedString(uiAttributedString *s); + +// uiAttributedStringString() returns the textual content of s as a +// '\0'-terminated UTF-8 string. The returned pointer is valid until +// the next change to the textual content of s. +_UI_EXTERN const char *uiAttributedStringString(const uiAttributedString *s); + +// uiAttributedStringLength() returns the number of UTF-8 bytes in +// the textual content of s, excluding the terminating '\0'. +_UI_EXTERN size_t uiAttributedStringLen(const uiAttributedString *s); + +// uiAttributedStringAppendUnattributed() adds the '\0'-terminated +// UTF-8 string str to the end of s. The new substring will be +// unattributed. +_UI_EXTERN void uiAttributedStringAppendUnattributed(uiAttributedString *s, const char *str); + +// uiAttributedStringInsertAtUnattributed() adds the '\0'-terminated +// UTF-8 string str to s at the byte position specified by at. The new +// substring will be unattributed; existing attributes will be moved +// along with their text. +_UI_EXTERN void uiAttributedStringInsertAtUnattributed(uiAttributedString *s, const char *str, size_t at); + +// TODO add the Append and InsertAtExtendingAttributes functions +// TODO and add functions that take a string + length + +// uiAttributedStringDelete() deletes the characters and attributes of +// s in the byte range [start, end). +_UI_EXTERN void uiAttributedStringDelete(uiAttributedString *s, size_t start, size_t end); + +// TODO add a function to uiAttributedString to get an attribute's value at a specific index or in a specific range, so we can edit + +// uiAttributedStringSetAttribute() sets a in the byte range [start, end) +// of s. Any existing attributes in that byte range of the same type are +// removed. s takes ownership of a; you should not use it after +// uiAttributedStringSetAttribute() returns. +_UI_EXTERN void uiAttributedStringSetAttribute(uiAttributedString *s, uiAttribute *a, size_t start, size_t end); + +// uiAttributedStringForEachAttribute() enumerates all the +// uiAttributes in s. It is an error to modify s in f. Within f, s still +// owns the attribute; you can neither free it nor save it for later +// use. +// TODO reword the above for consistency (TODO and find out what I meant by that) +// TODO define an enumeration order (or mark it as undefined); also define how consecutive runs of identical attributes are handled here and sync with the definition of uiAttributedString itself +_UI_EXTERN void uiAttributedStringForEachAttribute(const uiAttributedString *s, uiAttributedStringForEachAttributeFunc f, void *data); + +// TODO const correct this somehow (the implementation needs to mutate the structure) +_UI_EXTERN size_t uiAttributedStringNumGraphemes(uiAttributedString *s); + +// TODO const correct this somehow (the implementation needs to mutate the structure) +_UI_EXTERN size_t uiAttributedStringByteIndexToGrapheme(uiAttributedString *s, size_t pos); + +// TODO const correct this somehow (the implementation needs to mutate the structure) +_UI_EXTERN size_t uiAttributedStringGraphemeToByteIndex(uiAttributedString *s, size_t pos); + +// uiFontDescriptor provides a complete description of a font where +// one is needed. Currently, this means as the default font of a +// uiDrawTextLayout and as the data returned by uiFontButton. +// All the members operate like the respective uiAttributes. +typedef struct uiFontDescriptor uiFontDescriptor; + +struct uiFontDescriptor { + // TODO const-correct this or figure out how to deal with this when getting a value + char *Family; + double Size; + uiTextWeight Weight; + uiTextItalic Italic; + uiTextStretch Stretch; +}; + +// uiDrawTextLayout is a concrete representation of a +// uiAttributedString that can be displayed in a uiDrawContext. +// It includes information important for the drawing of a block of +// text, including the bounding box to wrap the text within, the +// alignment of lines of text within that box, areas to mark as +// being selected, and other things. +// +// Unlike uiAttributedString, the content of a uiDrawTextLayout is +// immutable once it has been created. +// +// TODO talk about OS-specific differences with text drawing that libui can't account for... +typedef struct uiDrawTextLayout uiDrawTextLayout; + +// uiDrawTextAlign specifies the alignment of lines of text in a +// uiDrawTextLayout. +// TODO should this really have Draw in the name? +_UI_ENUM(uiDrawTextAlign) { + uiDrawTextAlignLeft, + uiDrawTextAlignCenter, + uiDrawTextAlignRight, +}; + +// uiDrawTextLayoutParams describes a uiDrawTextLayout. +// DefaultFont is used to render any text that is not attributed +// sufficiently in String. Width determines the width of the bounding +// box of the text; the height is determined automatically. +typedef struct uiDrawTextLayoutParams uiDrawTextLayoutParams; + +// TODO const-correct this somehow +struct uiDrawTextLayoutParams { + uiAttributedString *String; + uiFontDescriptor *DefaultFont; + double Width; + uiDrawTextAlign Align; +}; + +// @role uiDrawTextLayout constructor +// uiDrawNewTextLayout() creates a new uiDrawTextLayout from +// the given parameters. +// +// TODO +// - allow creating a layout out of a substring +// - allow marking compositon strings +// - allow marking selections, even after creation +// - add the following functions: +// - uiDrawTextLayoutHeightForWidth() (returns the height that a layout would need to be to display the entire string at a given width) +// - uiDrawTextLayoutRangeForSize() (returns what substring would fit in a given size) +// - uiDrawTextLayoutNewWithHeight() (limits amount of string used by the height) +// - some function to fix up a range (for text editing) +_UI_EXTERN uiDrawTextLayout *uiDrawNewTextLayout(uiDrawTextLayoutParams *params); + +// @role uiDrawFreeTextLayout destructor +// uiDrawFreeTextLayout() frees tl. The underlying +// uiAttributedString is not freed. +_UI_EXTERN void uiDrawFreeTextLayout(uiDrawTextLayout *tl); + +// uiDrawText() draws tl in c with the top-left point of tl at (x, y). +_UI_EXTERN void uiDrawText(uiDrawContext *c, uiDrawTextLayout *tl, double x, double y); + +// uiDrawTextLayoutExtents() returns the width and height of tl +// in width and height. The returned width may be smaller than +// the width passed into uiDrawNewTextLayout() depending on +// how the text in tl is wrapped. Therefore, you can use this +// function to get the actual size of the text layout. +_UI_EXTERN void uiDrawTextLayoutExtents(uiDrawTextLayout *tl, double *width, double *height); + +// TODO metrics functions + +// TODO number of lines visible for clipping rect, range visible for clipping rect? + +// uiFontButton is a button that allows users to choose a font when they click on it. +typedef struct uiFontButton uiFontButton; +#define uiFontButton(this) ((uiFontButton *) (this)) +// uiFontButtonFont() returns the font currently selected in the uiFontButton in desc. +// uiFontButtonFont() allocates resources in desc; when you are done with the font, call uiFreeFontButtonFont() to release them. +// uiFontButtonFont() does not allocate desc itself; you must do so. +// TODO have a function that sets an entire font descriptor to a range in a uiAttributedString at once, for SetFont? +_UI_EXTERN void uiFontButtonFont(uiFontButton *b, uiFontDescriptor *desc); +// TOOD SetFont, mechanics +// uiFontButtonOnChanged() sets the function that is called when the font in the uiFontButton is changed. +_UI_EXTERN void uiFontButtonOnChanged(uiFontButton *b, void (*f)(uiFontButton *, void *), void *data); +// uiNewFontButton() creates a new uiFontButton. The default font selected into the uiFontButton is OS-defined. +_UI_EXTERN uiFontButton *uiNewFontButton(void); +// uiFreeFontButtonFont() frees resources allocated in desc by uiFontButtonFont(). +// After calling uiFreeFontButtonFont(), the contents of desc should be assumed to be undefined (though since you allocate desc itself, you can safely reuse desc for other font descriptors). +// Calling uiFreeFontButtonFont() on a uiFontDescriptor not returned by uiFontButtonFont() results in undefined behavior. +_UI_EXTERN void uiFreeFontButtonFont(uiFontDescriptor *desc); + +_UI_ENUM(uiModifiers) { + uiModifierCtrl = 1 << 0, + uiModifierAlt = 1 << 1, + uiModifierShift = 1 << 2, + uiModifierSuper = 1 << 3, +}; + +// TODO document drag captures +struct uiAreaMouseEvent { + // TODO document what these mean for scrolling areas + double X; + double Y; + + // TODO see draw above + double AreaWidth; + double AreaHeight; + + int Down; + int Up; + + int Count; + + uiModifiers Modifiers; + + uint64_t Held1To64; +}; + +_UI_ENUM(uiExtKey) { + uiExtKeyEscape = 1, + uiExtKeyInsert, // equivalent to "Help" on Apple keyboards + uiExtKeyDelete, + uiExtKeyHome, + uiExtKeyEnd, + uiExtKeyPageUp, + uiExtKeyPageDown, + uiExtKeyUp, + uiExtKeyDown, + uiExtKeyLeft, + uiExtKeyRight, + uiExtKeyF1, // F1..F12 are guaranteed to be consecutive + uiExtKeyF2, + uiExtKeyF3, + uiExtKeyF4, + uiExtKeyF5, + uiExtKeyF6, + uiExtKeyF7, + uiExtKeyF8, + uiExtKeyF9, + uiExtKeyF10, + uiExtKeyF11, + uiExtKeyF12, + uiExtKeyN0, // numpad keys; independent of Num Lock state + uiExtKeyN1, // N0..N9 are guaranteed to be consecutive + uiExtKeyN2, + uiExtKeyN3, + uiExtKeyN4, + uiExtKeyN5, + uiExtKeyN6, + uiExtKeyN7, + uiExtKeyN8, + uiExtKeyN9, + uiExtKeyNDot, + uiExtKeyNEnter, + uiExtKeyNAdd, + uiExtKeyNSubtract, + uiExtKeyNMultiply, + uiExtKeyNDivide, +}; + +struct uiAreaKeyEvent { + char Key; + uiExtKey ExtKey; + uiModifiers Modifier; + + uiModifiers Modifiers; + + int Up; +}; + +typedef struct uiColorButton uiColorButton; +#define uiColorButton(this) ((uiColorButton *) (this)) +_UI_EXTERN void uiColorButtonColor(uiColorButton *b, double *r, double *g, double *bl, double *a); +_UI_EXTERN void uiColorButtonSetColor(uiColorButton *b, double r, double g, double bl, double a); +_UI_EXTERN void uiColorButtonOnChanged(uiColorButton *b, void (*f)(uiColorButton *, void *), void *data); +_UI_EXTERN uiColorButton *uiNewColorButton(void); + +typedef struct uiForm uiForm; +#define uiForm(this) ((uiForm *) (this)) +_UI_EXTERN void uiFormAppend(uiForm *f, const char *label, uiControl *c, int stretchy); +_UI_EXTERN void uiFormDelete(uiForm *f, int index); +_UI_EXTERN int uiFormPadded(uiForm *f); +_UI_EXTERN void uiFormSetPadded(uiForm *f, int padded); +_UI_EXTERN uiForm *uiNewForm(void); + +_UI_ENUM(uiAlign) { + uiAlignFill, + uiAlignStart, + uiAlignCenter, + uiAlignEnd, +}; + +_UI_ENUM(uiAt) { + uiAtLeading, + uiAtTop, + uiAtTrailing, + uiAtBottom, +}; + +typedef struct uiGrid uiGrid; +#define uiGrid(this) ((uiGrid *) (this)) +_UI_EXTERN void uiGridAppend(uiGrid *g, uiControl *c, int left, int top, int xspan, int yspan, int hexpand, uiAlign halign, int vexpand, uiAlign valign); +_UI_EXTERN void uiGridInsertAt(uiGrid *g, uiControl *c, uiControl *existing, uiAt at, int xspan, int yspan, int hexpand, uiAlign halign, int vexpand, uiAlign valign); +_UI_EXTERN int uiGridPadded(uiGrid *g); +_UI_EXTERN void uiGridSetPadded(uiGrid *g, int padded); +_UI_EXTERN uiGrid *uiNewGrid(void); + +// uiImage stores an image for display on screen. +// +// Images are built from one or more representations, each with the +// same aspect ratio but a different pixel size. libui automatically +// selects the most appropriate representation for drawing the image +// when it comes time to draw the image; what this means depends +// on the pixel density of the target context. Therefore, one can use +// uiImage to draw higher-detailed images on higher-density +// displays. The typical use cases are either: +// +// - have just a single representation, at which point all screens +// use the same image, and thus uiImage acts like a simple +// bitmap image, or +// - have two images, one at normal resolution and one at 2x +// resolution; this matches the current expectations of some +// desktop systems at the time of writing (mid-2018) +// +// uiImage is very simple: it only supports premultiplied 32-bit +// RGBA images, and libui does not provide any image file loading +// or image format conversion utilities on top of that. +typedef struct uiImage uiImage; + +// @role uiImage constructor +// uiNewImage creates a new uiImage with the given width and +// height. This width and height should be the size in points of the +// image in the device-independent case; typically this is the 1x size. +// TODO for all uiImage functions: use const void * for const correctness +_UI_EXTERN uiImage *uiNewImage(double width, double height); + +// @role uiImage destructor +// uiFreeImage frees the given image and all associated resources. +_UI_EXTERN void uiFreeImage(uiImage *i); + +// uiImageAppend adds a representation to the uiImage. +// pixels should point to a byte array of premultiplied pixels +// stored in [R G B A] order (so ((uint8_t *) pixels)[0] is the R of the +// first pixel and [3] is the A of the first pixel). pixelWidth and +// pixelHeight is the size *in pixels* of the image, and pixelStride is +// the number *of bytes* per row of the pixels array. Therefore, +// pixels itself must be at least byteStride * pixelHeight bytes long. +// TODO see if we either need the stride or can provide a way to get the OS-preferred stride (in cairo we do) +_UI_EXTERN void uiImageAppend(uiImage *i, void *pixels, int pixelWidth, int pixelHeight, int byteStride); + +// uiTableValue stores a value to be passed along uiTable and +// uiTableModel. +// +// You do not create uiTableValues directly; instead, you create a +// uiTableValue of a given type using the specialized constructor +// functions. +// +// uiTableValues are immutable and the uiTableModel and uiTable +// take ownership of the uiTableValue object once returned, copying +// its contents as necessary. +typedef struct uiTableValue uiTableValue; + +// @role uiTableValue destructor +// uiFreeTableValue() frees a uiTableValue. You generally do not +// need to call this yourself, as uiTable and uiTableModel do this +// for you. In fact, it is an error to call this function on a uiTableValue +// that has been given to a uiTable or uiTableModel. You can call this, +// however, if you created a uiTableValue that you aren't going to +// use later, or if you called a uiTableModelHandler method directly +// and thus never transferred ownership of the uiTableValue. +_UI_EXTERN void uiFreeTableValue(uiTableValue *v); + +// uiTableValueType holds the possible uiTableValue types that may +// be returned by uiTableValueGetType(). Refer to the documentation +// for each type's constructor function for details on each type. +// TODO actually validate these +_UI_ENUM(uiTableValueType) { + uiTableValueTypeString, + uiTableValueTypeImage, + uiTableValueTypeInt, + uiTableValueTypeColor, +}; + +// uiTableValueGetType() returns the type of v. +// TODO I don't like this name +_UI_EXTERN uiTableValueType uiTableValueGetType(const uiTableValue *v); + +// uiNewTableValueString() returns a new uiTableValue that contains +// str. str is copied; you do not need to keep it alive after +// uiNewTableValueString() returns. +_UI_EXTERN uiTableValue *uiNewTableValueString(const char *str); + +// uiTableValueString() returns the string stored in v. The returned +// string is owned by v. It is an error to call this on a uiTableValue +// that does not hold a string. +_UI_EXTERN const char *uiTableValueString(const uiTableValue *v); + +// uiNewTableValueImage() returns a new uiTableValue that contains +// the given uiImage. +// +// Unlike other similar constructors, uiNewTableValueImage() does +// NOT copy the image. This is because images are comparatively +// larger than the other objects in question. Therefore, you MUST +// keep the image alive as long as the returned uiTableValue is alive. +// As a general rule, if libui calls a uiTableModelHandler method, the +// uiImage is safe to free once any of your code is once again +// executed. +_UI_EXTERN uiTableValue *uiNewTableValueImage(uiImage *img); + +// uiTableValueImage() returns the uiImage stored in v. As these +// images are not owned by v, you should not assume anything +// about the lifetime of the image (unless you created the image, +// and thus control its lifetime). It is an error to call this on a +// uiTableValue that does not hold an image. +_UI_EXTERN uiImage *uiTableValueImage(const uiTableValue *v); + +// uiNewTableValueInt() returns a uiTableValue that stores the given +// int. This can be used both for boolean values (nonzero is true, as +// in C) or progresses (in which case the valid range is -1..100 +// inclusive). +_UI_EXTERN uiTableValue *uiNewTableValueInt(int i); + +// uiTableValueInt() returns the int stored in v. It is an error to call +// this on a uiTableValue that does not store an int. +_UI_EXTERN int uiTableValueInt(const uiTableValue *v); + +// uiNewTableValueColor() returns a uiTableValue that stores the +// given color. +_UI_EXTERN uiTableValue *uiNewTableValueColor(double r, double g, double b, double a); + +// uiTableValueColor() returns the color stored in v. It is an error to +// call this on a uiTableValue that does not store a color. +// TODO define whether all this, for both uiTableValue and uiAttribute, is undefined behavior or a caught error +_UI_EXTERN void uiTableValueColor(const uiTableValue *v, double *r, double *g, double *b, double *a); + +// uiTableModel is an object that provides the data for a uiTable. +// This data is returned via methods you provide in the +// uiTableModelHandler struct. +// +// uiTableModel represents data using a table, but this table does +// not map directly to uiTable itself. Instead, you can have data +// columns which provide instructions for how to render a given +// uiTable's column — for instance, one model column can be used +// to give certain rows of a uiTable a different background color. +// Row numbers DO match with uiTable row numbers. +// +// Once created, the number and data types of columns of a +// uiTableModel cannot change. +// +// Row and column numbers start at 0. A uiTableModel can be +// associated with more than one uiTable at a time. +typedef struct uiTableModel uiTableModel; + +// uiTableModelHandler defines the methods that uiTableModel +// calls when it needs data. Once a uiTableModel is created, these +// methods cannot change. +typedef struct uiTableModelHandler uiTableModelHandler; + +// TODO validate ranges; validate types on each getter/setter call (? table columns only?) +struct uiTableModelHandler { + // NumColumns returns the number of model columns in the + // uiTableModel. This value must remain constant through the + // lifetime of the uiTableModel. This method is not guaranteed + // to be called depending on the system. + // TODO strongly check column numbers and types on all platforms so these clauses can go away + int (*NumColumns)(uiTableModelHandler *, uiTableModel *); + // ColumnType returns the value type of the data stored in + // the given model column of the uiTableModel. The returned + // values must remain constant through the lifetime of the + // uiTableModel. This method is not guaranteed to be called + // depending on the system. + uiTableValueType (*ColumnType)(uiTableModelHandler *, uiTableModel *, int); + // NumRows returns the number or rows in the uiTableModel. + // This value must be non-negative. + int (*NumRows)(uiTableModelHandler *, uiTableModel *); + // CellValue returns a uiTableValue corresponding to the model + // cell at (row, column). The type of the returned uiTableValue + // must match column's value type. Under some circumstances, + // NULL may be returned; refer to the various methods that add + // columns to uiTable for details. Once returned, the uiTable + // that calls CellValue will free the uiTableValue returned. + uiTableValue *(*CellValue)(uiTableModelHandler *mh, uiTableModel *m, int row, int column); + // SetCellValue changes the model cell value at (row, column) + // in the uiTableModel. Within this function, either do nothing + // to keep the current cell value or save the new cell value as + // appropriate. After SetCellValue is called, the uiTable will + // itself reload the table cell. Under certain conditions, the + // uiTableValue passed in can be NULL; refer to the various + // methods that add columns to uiTable for details. Once + // returned, the uiTable that called SetCellValue will free the + // uiTableValue passed in. + void (*SetCellValue)(uiTableModelHandler *, uiTableModel *, int, int, const uiTableValue *); +}; + +// @role uiTableModel constructor +// uiNewTableModel() creates a new uiTableModel with the given +// handler methods. +_UI_EXTERN uiTableModel *uiNewTableModel(uiTableModelHandler *mh); + +// @role uiTableModel destructor +// uiFreeTableModel() frees the given table model. It is an error to +// free table models currently associated with a uiTable. +_UI_EXTERN void uiFreeTableModel(uiTableModel *m); + +// uiTableModelRowInserted() tells any uiTable associated with m +// that a new row has been added to m at index index. You call +// this function when the number of rows in your model has +// changed; after calling it, NumRows() should returm the new row +// count. +_UI_EXTERN void uiTableModelRowInserted(uiTableModel *m, int newIndex); + +// uiTableModelRowChanged() tells any uiTable associated with m +// that the data in the row at index has changed. You do not need to +// call this in your SetCellValue() handlers, but you do need to call +// this if your data changes at some other point. +_UI_EXTERN void uiTableModelRowChanged(uiTableModel *m, int index); + +// uiTableModelRowDeleted() tells any uiTable associated with m +// that the row at index index has been deleted. You call this +// function when the number of rows in your model has changed; +// after calling it, NumRows() should returm the new row +// count. +// TODO for this and Inserted: make sure the "after" part is right; clarify if it's after returning or after calling +_UI_EXTERN void uiTableModelRowDeleted(uiTableModel *m, int oldIndex); +// TODO reordering/moving + +// uiTableModelColumnNeverEditable and +// uiTableModelColumnAlwaysEditable are the value of an editable +// model column parameter to one of the uiTable create column +// functions; if used, that jparticular uiTable colum is not editable +// by the user and always editable by the user, respectively. +#define uiTableModelColumnNeverEditable (-1) +#define uiTableModelColumnAlwaysEditable (-2) + +// uiTableTextColumnOptionalParams are the optional parameters +// that control the appearance of the text column of a uiTable. +typedef struct uiTableTextColumnOptionalParams uiTableTextColumnOptionalParams; + +// uiTableParams defines the parameters passed to uiNewTable(). +typedef struct uiTableParams uiTableParams; + +struct uiTableTextColumnOptionalParams { + // ColorModelColumn is the model column containing the + // text color of this uiTable column's text, or -1 to use the + // default color. + // + // If CellValue() for this column for any cell returns NULL, that + // cell will also use the default text color. + int ColorModelColumn; +}; + +struct uiTableParams { + // Model is the uiTableModel to use for this uiTable. + // This parameter cannot be NULL. + uiTableModel *Model; + // RowBackgroundColorModelColumn is a model column + // number that defines the background color used for the + // entire row in the uiTable, or -1 to use the default color for + // all rows. + // + // If CellValue() for this column for any row returns NULL, that + // row will also use the default background color. + int RowBackgroundColorModelColumn; +}; + +// uiTable is a uiControl that shows tabular data, allowing users to +// manipulate rows of such data at a time. +typedef struct uiTable uiTable; +#define uiTable(this) ((uiTable *) (this)) + +// uiTableAppendTextColumn() appends a text column to t. +// name is displayed in the table header. +// textModelColumn is where the text comes from. +// If a row is editable according to textEditableModelColumn, +// SetCellValue() is called with textModelColumn as the column. +_UI_EXTERN void uiTableAppendTextColumn(uiTable *t, + const char *name, + int textModelColumn, + int textEditableModelColumn, + uiTableTextColumnOptionalParams *textParams); + +// uiTableAppendImageColumn() appends an image column to t. +// Images are drawn at icon size, appropriate to the pixel density +// of the screen showing the uiTable. +_UI_EXTERN void uiTableAppendImageColumn(uiTable *t, + const char *name, + int imageModelColumn); + +// uiTableAppendImageTextColumn() appends a column to t that +// shows both an image and text. +_UI_EXTERN void uiTableAppendImageTextColumn(uiTable *t, + const char *name, + int imageModelColumn, + int textModelColumn, + int textEditableModelColumn, + uiTableTextColumnOptionalParams *textParams); + +// uiTableAppendCheckboxColumn appends a column to t that +// contains a checkbox that the user can interact with (assuming the +// checkbox is editable). SetCellValue() will be called with +// checkboxModelColumn as the column in this case. +_UI_EXTERN void uiTableAppendCheckboxColumn(uiTable *t, + const char *name, + int checkboxModelColumn, + int checkboxEditableModelColumn); + +// uiTableAppendCheckboxTextColumn() appends a column to t +// that contains both a checkbox and text. +_UI_EXTERN void uiTableAppendCheckboxTextColumn(uiTable *t, + const char *name, + int checkboxModelColumn, + int checkboxEditableModelColumn, + int textModelColumn, + int textEditableModelColumn, + uiTableTextColumnOptionalParams *textParams); + +// uiTableAppendProgressBarColumn() appends a column to t +// that displays a progress bar. These columns work like +// uiProgressBar: a cell value of 0..100 displays that percentage, and +// a cell value of -1 displays an indeterminate progress bar. +_UI_EXTERN void uiTableAppendProgressBarColumn(uiTable *t, + const char *name, + int progressModelColumn); + +// uiTableAppendButtonColumn() appends a column to t +// that shows a button that the user can click on. When the user +// does click on the button, SetCellValue() is called with a NULL +// value and buttonModelColumn as the column. +// CellValue() on buttonModelColumn should return the text to show +// in the button. +_UI_EXTERN void uiTableAppendButtonColumn(uiTable *t, + const char *name, + int buttonModelColumn, + int buttonClickableModelColumn); + +// uiNewTable() creates a new uiTable with the specified parameters. +_UI_EXTERN uiTable *uiNewTable(uiTableParams *params); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/dep/libui/ui_darwin.h b/dep/libui/ui_darwin.h new file mode 100644 index 0000000..c9c6ad5 --- /dev/null +++ b/dep/libui/ui_darwin.h @@ -0,0 +1,224 @@ +// 7 april 2015 + +/* +This file assumes that you have imported and "ui.h" beforehand. It provides API-specific functions for interfacing with foreign controls on Mac OS X. +*/ + +#ifndef __LIBUI_UI_DARWIN_H__ +#define __LIBUI_UI_DARWIN_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct uiDarwinControl uiDarwinControl; +struct uiDarwinControl { + uiControl c; + uiControl *parent; + BOOL enabled; + BOOL visible; + void (*SyncEnableState)(uiDarwinControl *, int); + void (*SetSuperview)(uiDarwinControl *, NSView *); + BOOL (*HugsTrailingEdge)(uiDarwinControl *); + BOOL (*HugsBottom)(uiDarwinControl *); + void (*ChildEdgeHuggingChanged)(uiDarwinControl *); + NSLayoutPriority (*HuggingPriority)(uiDarwinControl *, NSLayoutConstraintOrientation); + void (*SetHuggingPriority)(uiDarwinControl *, NSLayoutPriority, NSLayoutConstraintOrientation); + void (*ChildVisibilityChanged)(uiDarwinControl *); +}; +#define uiDarwinControl(this) ((uiDarwinControl *) (this)) +// TODO document +_UI_EXTERN void uiDarwinControlSyncEnableState(uiDarwinControl *, int); +_UI_EXTERN void uiDarwinControlSetSuperview(uiDarwinControl *, NSView *); +_UI_EXTERN BOOL uiDarwinControlHugsTrailingEdge(uiDarwinControl *); +_UI_EXTERN BOOL uiDarwinControlHugsBottom(uiDarwinControl *); +_UI_EXTERN void uiDarwinControlChildEdgeHuggingChanged(uiDarwinControl *); +_UI_EXTERN NSLayoutPriority uiDarwinControlHuggingPriority(uiDarwinControl *, NSLayoutConstraintOrientation); +_UI_EXTERN void uiDarwinControlSetHuggingPriority(uiDarwinControl *, NSLayoutPriority, NSLayoutConstraintOrientation); +_UI_EXTERN void uiDarwinControlChildVisibilityChanged(uiDarwinControl *); + +#define uiDarwinControlDefaultDestroy(type, handlefield) \ + static void type ## Destroy(uiControl *c) \ + { \ + [type(c)->handlefield release]; \ + uiFreeControl(c); \ + } +#define uiDarwinControlDefaultHandle(type, handlefield) \ + static uintptr_t type ## Handle(uiControl *c) \ + { \ + return (uintptr_t) (type(c)->handlefield); \ + } +#define uiDarwinControlDefaultParent(type, handlefield) \ + static uiControl *type ## Parent(uiControl *c) \ + { \ + return uiDarwinControl(c)->parent; \ + } +#define uiDarwinControlDefaultSetParent(type, handlefield) \ + static void type ## SetParent(uiControl *c, uiControl *parent) \ + { \ + uiControlVerifySetParent(c, parent); \ + uiDarwinControl(c)->parent = parent; \ + } +#define uiDarwinControlDefaultToplevel(type, handlefield) \ + static int type ## Toplevel(uiControl *c) \ + { \ + return 0; \ + } +#define uiDarwinControlDefaultVisible(type, handlefield) \ + static int type ## Visible(uiControl *c) \ + { \ + return uiDarwinControl(c)->visible; \ + } +#define uiDarwinControlDefaultShow(type, handlefield) \ + static void type ## Show(uiControl *c) \ + { \ + uiDarwinControl(c)->visible = YES; \ + [type(c)->handlefield setHidden:NO]; \ + uiDarwinNotifyVisibilityChanged(uiDarwinControl(c)); \ + } +#define uiDarwinControlDefaultHide(type, handlefield) \ + static void type ## Hide(uiControl *c) \ + { \ + uiDarwinControl(c)->visible = NO; \ + [type(c)->handlefield setHidden:YES]; \ + uiDarwinNotifyVisibilityChanged(uiDarwinControl(c)); \ + } +#define uiDarwinControlDefaultEnabled(type, handlefield) \ + static int type ## Enabled(uiControl *c) \ + { \ + return uiDarwinControl(c)->enabled; \ + } +#define uiDarwinControlDefaultEnable(type, handlefield) \ + static void type ## Enable(uiControl *c) \ + { \ + uiDarwinControl(c)->enabled = YES; \ + uiDarwinControlSyncEnableState(uiDarwinControl(c), uiControlEnabledToUser(c)); \ + } +#define uiDarwinControlDefaultDisable(type, handlefield) \ + static void type ## Disable(uiControl *c) \ + { \ + uiDarwinControl(c)->enabled = NO; \ + uiDarwinControlSyncEnableState(uiDarwinControl(c), uiControlEnabledToUser(c)); \ + } +#define uiDarwinControlDefaultSyncEnableState(type, handlefield) \ + static void type ## SyncEnableState(uiDarwinControl *c, int enabled) \ + { \ + if (uiDarwinShouldStopSyncEnableState(c, enabled)) \ + return; \ + if ([type(c)->handlefield respondsToSelector:@selector(setEnabled:)]) \ + [((id) (type(c)->handlefield)) setEnabled:enabled]; /* id cast to make compiler happy; thanks mikeash in irc.freenode.net/#macdev */ \ + } +#define uiDarwinControlDefaultSetSuperview(type, handlefield) \ + static void type ## SetSuperview(uiDarwinControl *c, NSView *superview) \ + { \ + [type(c)->handlefield setTranslatesAutoresizingMaskIntoConstraints:NO]; \ + if (superview == nil) \ + [type(c)->handlefield removeFromSuperview]; \ + else \ + [superview addSubview:type(c)->handlefield]; \ + } +#define uiDarwinControlDefaultHugsTrailingEdge(type, handlefield) \ + static BOOL type ## HugsTrailingEdge(uiDarwinControl *c) \ + { \ + return YES; /* always hug by default */ \ + } +#define uiDarwinControlDefaultHugsBottom(type, handlefield) \ + static BOOL type ## HugsBottom(uiDarwinControl *c) \ + { \ + return YES; /* always hug by default */ \ + } +#define uiDarwinControlDefaultChildEdgeHuggingChanged(type, handlefield) \ + static void type ## ChildEdgeHuggingChanged(uiDarwinControl *c) \ + { \ + /* do nothing */ \ + } +#define uiDarwinControlDefaultHuggingPriority(type, handlefield) \ + static NSLayoutPriority type ## HuggingPriority(uiDarwinControl *c, NSLayoutConstraintOrientation orientation) \ + { \ + return [type(c)->handlefield contentHuggingPriorityForOrientation:orientation]; \ + } +#define uiDarwinControlDefaultSetHuggingPriority(type, handlefield) \ + static void type ## SetHuggingPriority(uiDarwinControl *c, NSLayoutPriority priority, NSLayoutConstraintOrientation orientation) \ + { \ + [type(c)->handlefield setContentHuggingPriority:priority forOrientation:orientation]; \ + } +#define uiDarwinControlDefaultChildVisibilityChanged(type, handlefield) \ + static void type ## ChildVisibilityChanged(uiDarwinControl *c) \ + { \ + /* do nothing */ \ + } + +#define uiDarwinControlAllDefaultsExceptDestroy(type, handlefield) \ + uiDarwinControlDefaultHandle(type, handlefield) \ + uiDarwinControlDefaultParent(type, handlefield) \ + uiDarwinControlDefaultSetParent(type, handlefield) \ + uiDarwinControlDefaultToplevel(type, handlefield) \ + uiDarwinControlDefaultVisible(type, handlefield) \ + uiDarwinControlDefaultShow(type, handlefield) \ + uiDarwinControlDefaultHide(type, handlefield) \ + uiDarwinControlDefaultEnabled(type, handlefield) \ + uiDarwinControlDefaultEnable(type, handlefield) \ + uiDarwinControlDefaultDisable(type, handlefield) \ + uiDarwinControlDefaultSyncEnableState(type, handlefield) \ + uiDarwinControlDefaultSetSuperview(type, handlefield) \ + uiDarwinControlDefaultHugsTrailingEdge(type, handlefield) \ + uiDarwinControlDefaultHugsBottom(type, handlefield) \ + uiDarwinControlDefaultChildEdgeHuggingChanged(type, handlefield) \ + uiDarwinControlDefaultHuggingPriority(type, handlefield) \ + uiDarwinControlDefaultSetHuggingPriority(type, handlefield) \ + uiDarwinControlDefaultChildVisibilityChanged(type, handlefield) + +#define uiDarwinControlAllDefaults(type, handlefield) \ + uiDarwinControlDefaultDestroy(type, handlefield) \ + uiDarwinControlAllDefaultsExceptDestroy(type, handlefield) + +// TODO document +#define uiDarwinNewControl(type, var) \ + var = type(uiDarwinAllocControl(sizeof (type), type ## Signature, #type)); \ + uiControl(var)->Destroy = type ## Destroy; \ + uiControl(var)->Handle = type ## Handle; \ + uiControl(var)->Parent = type ## Parent; \ + uiControl(var)->SetParent = type ## SetParent; \ + uiControl(var)->Toplevel = type ## Toplevel; \ + uiControl(var)->Visible = type ## Visible; \ + uiControl(var)->Show = type ## Show; \ + uiControl(var)->Hide = type ## Hide; \ + uiControl(var)->Enabled = type ## Enabled; \ + uiControl(var)->Enable = type ## Enable; \ + uiControl(var)->Disable = type ## Disable; \ + uiDarwinControl(var)->SyncEnableState = type ## SyncEnableState; \ + uiDarwinControl(var)->SetSuperview = type ## SetSuperview; \ + uiDarwinControl(var)->HugsTrailingEdge = type ## HugsTrailingEdge; \ + uiDarwinControl(var)->HugsBottom = type ## HugsBottom; \ + uiDarwinControl(var)->ChildEdgeHuggingChanged = type ## ChildEdgeHuggingChanged; \ + uiDarwinControl(var)->HuggingPriority = type ## HuggingPriority; \ + uiDarwinControl(var)->SetHuggingPriority = type ## SetHuggingPriority; \ + uiDarwinControl(var)->ChildVisibilityChanged = type ## ChildVisibilityChanged; \ + uiDarwinControl(var)->visible = YES; \ + uiDarwinControl(var)->enabled = YES; +// TODO document +_UI_EXTERN uiDarwinControl *uiDarwinAllocControl(size_t n, uint32_t typesig, const char *typenamestr); + +// Use this function as a shorthand for setting control fonts. +_UI_EXTERN void uiDarwinSetControlFont(NSControl *c, NSControlSize size); + +// You can use this function from within your control implementations to return text strings that can be freed with uiFreeText(). +_UI_EXTERN char *uiDarwinNSStringToText(NSString *); + +// TODO document +_UI_EXTERN BOOL uiDarwinShouldStopSyncEnableState(uiDarwinControl *, BOOL); + +// TODO document +_UI_EXTERN void uiDarwinNotifyEdgeHuggingChanged(uiDarwinControl *); +_UI_EXTERN void uiDarwinNotifyVisibilityChanged(uiDarwinControl *c); + +// TODO document +// TODO document that values should not be cached +_UI_EXTERN CGFloat uiDarwinMarginAmount(void *reserved); +_UI_EXTERN CGFloat uiDarwinPaddingAmount(void *reserved); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/dep/libui/ui_unix.h b/dep/libui/ui_unix.h new file mode 100644 index 0000000..ed01926 --- /dev/null +++ b/dep/libui/ui_unix.h @@ -0,0 +1,144 @@ +// 7 april 2015 + +/* +This file assumes that you have included and "ui.h" beforehand. It provides API-specific functions for interfacing with foreign controls on Unix systems that use GTK+ to provide their UI (currently all except Mac OS X). +*/ + +#ifndef __LIBUI_UI_UNIX_H__ +#define __LIBUI_UI_UNIX_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct uiUnixControl uiUnixControl; +struct uiUnixControl { + uiControl c; + uiControl *parent; + gboolean addedBefore; + gboolean explicitlyHidden; + void (*SetContainer)(uiUnixControl *, GtkContainer *, gboolean); +}; +#define uiUnixControl(this) ((uiUnixControl *) (this)) +// TODO document +_UI_EXTERN void uiUnixControlSetContainer(uiUnixControl *, GtkContainer *, gboolean); + +#define uiUnixControlDefaultDestroy(type) \ + static void type ## Destroy(uiControl *c) \ + { \ + /* TODO is this safe on floating refs? */ \ + g_object_unref(type(c)->widget); \ + uiFreeControl(c); \ + } +#define uiUnixControlDefaultHandle(type) \ + static uintptr_t type ## Handle(uiControl *c) \ + { \ + return (uintptr_t) (type(c)->widget); \ + } +#define uiUnixControlDefaultParent(type) \ + static uiControl *type ## Parent(uiControl *c) \ + { \ + return uiUnixControl(c)->parent; \ + } +#define uiUnixControlDefaultSetParent(type) \ + static void type ## SetParent(uiControl *c, uiControl *parent) \ + { \ + uiControlVerifySetParent(c, parent); \ + uiUnixControl(c)->parent = parent; \ + } +#define uiUnixControlDefaultToplevel(type) \ + static int type ## Toplevel(uiControl *c) \ + { \ + return 0; \ + } +#define uiUnixControlDefaultVisible(type) \ + static int type ## Visible(uiControl *c) \ + { \ + return gtk_widget_get_visible(type(c)->widget); \ + } +#define uiUnixControlDefaultShow(type) \ + static void type ## Show(uiControl *c) \ + { \ + /*TODO part of massive hack about hidden before*/uiUnixControl(c)->explicitlyHidden=FALSE; \ + gtk_widget_show(type(c)->widget); \ + } +#define uiUnixControlDefaultHide(type) \ + static void type ## Hide(uiControl *c) \ + { \ + /*TODO part of massive hack about hidden before*/uiUnixControl(c)->explicitlyHidden=TRUE; \ + gtk_widget_hide(type(c)->widget); \ + } +#define uiUnixControlDefaultEnabled(type) \ + static int type ## Enabled(uiControl *c) \ + { \ + return gtk_widget_get_sensitive(type(c)->widget); \ + } +#define uiUnixControlDefaultEnable(type) \ + static void type ## Enable(uiControl *c) \ + { \ + gtk_widget_set_sensitive(type(c)->widget, TRUE); \ + } +#define uiUnixControlDefaultDisable(type) \ + static void type ## Disable(uiControl *c) \ + { \ + gtk_widget_set_sensitive(type(c)->widget, FALSE); \ + } +// TODO this whole addedBefore stuff is a MASSIVE HACK. +#define uiUnixControlDefaultSetContainer(type) \ + static void type ## SetContainer(uiUnixControl *c, GtkContainer *container, gboolean remove) \ + { \ + if (!uiUnixControl(c)->addedBefore) { \ + g_object_ref_sink(type(c)->widget); /* our own reference, which we release in Destroy() */ \ + /* massive hack notes: without any of this, nothing gets shown when we show a window; without the if, all things get shown even if some were explicitly hidden (TODO why don't we just show everything except windows on create? */ \ + /*TODO*/if(!uiUnixControl(c)->explicitlyHidden) gtk_widget_show(type(c)->widget); \ + uiUnixControl(c)->addedBefore = TRUE; \ + } \ + if (remove) \ + gtk_container_remove(container, type(c)->widget); \ + else \ + gtk_container_add(container, type(c)->widget); \ + } + +#define uiUnixControlAllDefaultsExceptDestroy(type) \ + uiUnixControlDefaultHandle(type) \ + uiUnixControlDefaultParent(type) \ + uiUnixControlDefaultSetParent(type) \ + uiUnixControlDefaultToplevel(type) \ + uiUnixControlDefaultVisible(type) \ + uiUnixControlDefaultShow(type) \ + uiUnixControlDefaultHide(type) \ + uiUnixControlDefaultEnabled(type) \ + uiUnixControlDefaultEnable(type) \ + uiUnixControlDefaultDisable(type) \ + uiUnixControlDefaultSetContainer(type) + +#define uiUnixControlAllDefaults(type) \ + uiUnixControlDefaultDestroy(type) \ + uiUnixControlAllDefaultsExceptDestroy(type) + +// TODO document +#define uiUnixNewControl(type, var) \ + var = type(uiUnixAllocControl(sizeof (type), type ## Signature, #type)); \ + uiControl(var)->Destroy = type ## Destroy; \ + uiControl(var)->Handle = type ## Handle; \ + uiControl(var)->Parent = type ## Parent; \ + uiControl(var)->SetParent = type ## SetParent; \ + uiControl(var)->Toplevel = type ## Toplevel; \ + uiControl(var)->Visible = type ## Visible; \ + uiControl(var)->Show = type ## Show; \ + uiControl(var)->Hide = type ## Hide; \ + uiControl(var)->Enabled = type ## Enabled; \ + uiControl(var)->Enable = type ## Enable; \ + uiControl(var)->Disable = type ## Disable; \ + uiUnixControl(var)->SetContainer = type ## SetContainer; +// TODO document +_UI_EXTERN uiUnixControl *uiUnixAllocControl(size_t n, uint32_t typesig, const char *typenamestr); + +// uiUnixStrdupText() takes the given string and produces a copy of it suitable for being freed by uiFreeText(). +_UI_EXTERN char *uiUnixStrdupText(const char *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/dep/libui/ui_windows.h b/dep/libui/ui_windows.h new file mode 100644 index 0000000..69dda36 --- /dev/null +++ b/dep/libui/ui_windows.h @@ -0,0 +1,267 @@ +// 21 april 2016 + +/* +This file assumes that you have included and "ui.h" beforehand. It provides API-specific functions for interfacing with foreign controls in Windows. +*/ + +#ifndef __LIBUI_UI_WINDOWS_H__ +#define __LIBUI_UI_WINDOWS_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct uiWindowsSizing uiWindowsSizing; + +typedef struct uiWindowsControl uiWindowsControl; +struct uiWindowsControl { + uiControl c; + uiControl *parent; + // TODO this should be int on both os x and windows + BOOL enabled; + BOOL visible; + void (*SyncEnableState)(uiWindowsControl *, int); + void (*SetParentHWND)(uiWindowsControl *, HWND); + void (*MinimumSize)(uiWindowsControl *, int *, int *); + void (*MinimumSizeChanged)(uiWindowsControl *); + void (*LayoutRect)(uiWindowsControl *c, RECT *r); + void (*AssignControlIDZOrder)(uiWindowsControl *, LONG_PTR *, HWND *); + void (*ChildVisibilityChanged)(uiWindowsControl *); +}; +#define uiWindowsControl(this) ((uiWindowsControl *) (this)) +// TODO document +_UI_EXTERN void uiWindowsControlSyncEnableState(uiWindowsControl *, int); +_UI_EXTERN void uiWindowsControlSetParentHWND(uiWindowsControl *, HWND); +_UI_EXTERN void uiWindowsControlMinimumSize(uiWindowsControl *, int *, int *); +_UI_EXTERN void uiWindowsControlMinimumSizeChanged(uiWindowsControl *); +_UI_EXTERN void uiWindowsControlLayoutRect(uiWindowsControl *, RECT *); +_UI_EXTERN void uiWindowsControlAssignControlIDZOrder(uiWindowsControl *, LONG_PTR *, HWND *); +_UI_EXTERN void uiWindowsControlChildVisibilityChanged(uiWindowsControl *); + +// TODO document +#define uiWindowsControlDefaultDestroy(type) \ + static void type ## Destroy(uiControl *c) \ + { \ + uiWindowsEnsureDestroyWindow(type(c)->hwnd); \ + uiFreeControl(c); \ + } +#define uiWindowsControlDefaultHandle(type) \ + static uintptr_t type ## Handle(uiControl *c) \ + { \ + return (uintptr_t) (type(c)->hwnd); \ + } +#define uiWindowsControlDefaultParent(type) \ + static uiControl *type ## Parent(uiControl *c) \ + { \ + return uiWindowsControl(c)->parent; \ + } +#define uiWindowsControlDefaultSetParent(type) \ + static void type ## SetParent(uiControl *c, uiControl *parent) \ + { \ + uiControlVerifySetParent(c, parent); \ + uiWindowsControl(c)->parent = parent; \ + } +#define uiWindowsControlDefaultToplevel(type) \ + static int type ## Toplevel(uiControl *c) \ + { \ + return 0; \ + } +#define uiWindowsControlDefaultVisible(type) \ + static int type ## Visible(uiControl *c) \ + { \ + return uiWindowsControl(c)->visible; \ + } +#define uiWindowsControlDefaultShow(type) \ + static void type ## Show(uiControl *c) \ + { \ + uiWindowsControl(c)->visible = 1; \ + ShowWindow(type(c)->hwnd, SW_SHOW); \ + uiWindowsControlNotifyVisibilityChanged(uiWindowsControl(c)); \ + } +#define uiWindowsControlDefaultHide(type) \ + static void type ## Hide(uiControl *c) \ + { \ + uiWindowsControl(c)->visible = 0; \ + ShowWindow(type(c)->hwnd, SW_HIDE); \ + uiWindowsControlNotifyVisibilityChanged(uiWindowsControl(c)); \ + } +#define uiWindowsControlDefaultEnabled(type) \ + static int type ## Enabled(uiControl *c) \ + { \ + return uiWindowsControl(c)->enabled; \ + } +#define uiWindowsControlDefaultEnable(type) \ + static void type ## Enable(uiControl *c) \ + { \ + uiWindowsControl(c)->enabled = 1; \ + uiWindowsControlSyncEnableState(uiWindowsControl(c), uiControlEnabledToUser(c)); \ + } +#define uiWindowsControlDefaultDisable(type) \ + static void type ## Disable(uiControl *c) \ + { \ + uiWindowsControl(c)->enabled = 0; \ + uiWindowsControlSyncEnableState(uiWindowsControl(c), uiControlEnabledToUser(c)); \ + } +#define uiWindowsControlDefaultSyncEnableState(type) \ + static void type ## SyncEnableState(uiWindowsControl *c, int enabled) \ + { \ + if (uiWindowsShouldStopSyncEnableState(c, enabled)) \ + return; \ + EnableWindow(type(c)->hwnd, enabled); \ + } +#define uiWindowsControlDefaultSetParentHWND(type) \ + static void type ## SetParentHWND(uiWindowsControl *c, HWND parent) \ + { \ + uiWindowsEnsureSetParentHWND(type(c)->hwnd, parent); \ + } +// note that there is no uiWindowsControlDefaultMinimumSize(); you MUST define this yourself! +#define uiWindowsControlDefaultMinimumSizeChanged(type) \ + static void type ## MinimumSizeChanged(uiWindowsControl *c) \ + { \ + if (uiWindowsControlTooSmall(c)) { \ + uiWindowsControlContinueMinimumSizeChanged(c); \ + return; \ + } \ + /* otherwise do nothing; we have no children */ \ + } +#define uiWindowsControlDefaultLayoutRect(type) \ + static void type ## LayoutRect(uiWindowsControl *c, RECT *r) \ + { \ + /* use the window rect as we include the non-client area in the sizes */ \ + uiWindowsEnsureGetWindowRect(type(c)->hwnd, r); \ + } +#define uiWindowsControlDefaultAssignControlIDZOrder(type) \ + static void type ## AssignControlIDZOrder(uiWindowsControl *c, LONG_PTR *controlID, HWND *insertAfter) \ + { \ + uiWindowsEnsureAssignControlIDZOrder(type(c)->hwnd, controlID, insertAfter); \ + } +#define uiWindowsControlDefaultChildVisibilityChanged(type) \ + static void type ## ChildVisibilityChanged(uiWindowsControl *c) \ + { \ + /* do nothing */ \ + } + +#define uiWindowsControlAllDefaultsExceptDestroy(type) \ + uiWindowsControlDefaultHandle(type) \ + uiWindowsControlDefaultParent(type) \ + uiWindowsControlDefaultSetParent(type) \ + uiWindowsControlDefaultToplevel(type) \ + uiWindowsControlDefaultVisible(type) \ + uiWindowsControlDefaultShow(type) \ + uiWindowsControlDefaultHide(type) \ + uiWindowsControlDefaultEnabled(type) \ + uiWindowsControlDefaultEnable(type) \ + uiWindowsControlDefaultDisable(type) \ + uiWindowsControlDefaultSyncEnableState(type) \ + uiWindowsControlDefaultSetParentHWND(type) \ + uiWindowsControlDefaultMinimumSizeChanged(type) \ + uiWindowsControlDefaultLayoutRect(type) \ + uiWindowsControlDefaultAssignControlIDZOrder(type) \ + uiWindowsControlDefaultChildVisibilityChanged(type) + +#define uiWindowsControlAllDefaults(type) \ + uiWindowsControlDefaultDestroy(type) \ + uiWindowsControlAllDefaultsExceptDestroy(type) + +// TODO document +#define uiWindowsNewControl(type, var) \ + var = type(uiWindowsAllocControl(sizeof (type), type ## Signature, #type)); \ + uiControl(var)->Destroy = type ## Destroy; \ + uiControl(var)->Handle = type ## Handle; \ + uiControl(var)->Parent = type ## Parent; \ + uiControl(var)->SetParent = type ## SetParent; \ + uiControl(var)->Toplevel = type ## Toplevel; \ + uiControl(var)->Visible = type ## Visible; \ + uiControl(var)->Show = type ## Show; \ + uiControl(var)->Hide = type ## Hide; \ + uiControl(var)->Enabled = type ## Enabled; \ + uiControl(var)->Enable = type ## Enable; \ + uiControl(var)->Disable = type ## Disable; \ + uiWindowsControl(var)->SyncEnableState = type ## SyncEnableState; \ + uiWindowsControl(var)->SetParentHWND = type ## SetParentHWND; \ + uiWindowsControl(var)->MinimumSize = type ## MinimumSize; \ + uiWindowsControl(var)->MinimumSizeChanged = type ## MinimumSizeChanged; \ + uiWindowsControl(var)->LayoutRect = type ## LayoutRect; \ + uiWindowsControl(var)->AssignControlIDZOrder = type ## AssignControlIDZOrder; \ + uiWindowsControl(var)->ChildVisibilityChanged = type ## ChildVisibilityChanged; \ + uiWindowsControl(var)->visible = 1; \ + uiWindowsControl(var)->enabled = 1; +// TODO document +_UI_EXTERN uiWindowsControl *uiWindowsAllocControl(size_t n, uint32_t typesig, const char *typenamestr); + +// TODO document +_UI_EXTERN HWND uiWindowsEnsureCreateControlHWND(DWORD dwExStyle, LPCWSTR lpClassName, LPCWSTR lpWindowName, DWORD dwStyle, HINSTANCE hInstance, LPVOID lpParam, BOOL useStandardControlFont); + +// TODO document +_UI_EXTERN void uiWindowsEnsureDestroyWindow(HWND hwnd); + +// TODO document +// TODO document that this should only be used in SetParentHWND() implementations +_UI_EXTERN void uiWindowsEnsureSetParentHWND(HWND hwnd, HWND parent); + +// TODO document +_UI_EXTERN void uiWindowsEnsureAssignControlIDZOrder(HWND hwnd, LONG_PTR *controlID, HWND *insertAfter); + +// TODO document +_UI_EXTERN void uiWindowsEnsureGetClientRect(HWND hwnd, RECT *r); +_UI_EXTERN void uiWindowsEnsureGetWindowRect(HWND hwnd, RECT *r); + +// TODO document +_UI_EXTERN char *uiWindowsWindowText(HWND hwnd); +_UI_EXTERN void uiWindowsSetWindowText(HWND hwnd, const char *text); + +// TODO document +_UI_EXTERN int uiWindowsWindowTextWidth(HWND hwnd); + +// TODO document +// TODO point out this should only be used in a resize cycle +_UI_EXTERN void uiWindowsEnsureMoveWindowDuringResize(HWND hwnd, int x, int y, int width, int height); + +// TODO document +_UI_EXTERN void uiWindowsRegisterWM_COMMANDHandler(HWND hwnd, BOOL (*handler)(uiControl *, HWND, WORD, LRESULT *), uiControl *c); +_UI_EXTERN void uiWindowsUnregisterWM_COMMANDHandler(HWND hwnd); + +// TODO document +_UI_EXTERN void uiWindowsRegisterWM_NOTIFYHandler(HWND hwnd, BOOL (*handler)(uiControl *, HWND, NMHDR *, LRESULT *), uiControl *c); +_UI_EXTERN void uiWindowsUnregisterWM_NOTIFYHandler(HWND hwnd); + +// TODO document +_UI_EXTERN void uiWindowsRegisterWM_HSCROLLHandler(HWND hwnd, BOOL (*handler)(uiControl *, HWND, WORD, LRESULT *), uiControl *c); +_UI_EXTERN void uiWindowsUnregisterWM_HSCROLLHandler(HWND hwnd); + +// TODO document +_UI_EXTERN void uiWindowsRegisterReceiveWM_WININICHANGE(HWND hwnd); +_UI_EXTERN void uiWindowsUnregisterReceiveWM_WININICHANGE(HWND hwnd); + +// TODO document +typedef struct uiWindowsSizing uiWindowsSizing; +struct uiWindowsSizing { + int BaseX; + int BaseY; + LONG InternalLeading; +}; +_UI_EXTERN void uiWindowsGetSizing(HWND hwnd, uiWindowsSizing *sizing); +_UI_EXTERN void uiWindowsSizingDlgUnitsToPixels(uiWindowsSizing *sizing, int *x, int *y); +_UI_EXTERN void uiWindowsSizingStandardPadding(uiWindowsSizing *sizing, int *x, int *y); + +// TODO document +_UI_EXTERN HWND uiWindowsMakeContainer(uiWindowsControl *c, void (*onResize)(uiWindowsControl *)); + +// TODO document +_UI_EXTERN BOOL uiWindowsControlTooSmall(uiWindowsControl *c); +_UI_EXTERN void uiWindowsControlContinueMinimumSizeChanged(uiWindowsControl *c); + +// TODO document +_UI_EXTERN void uiWindowsControlAssignSoleControlIDZOrder(uiWindowsControl *); + +// TODO document +_UI_EXTERN BOOL uiWindowsShouldStopSyncEnableState(uiWindowsControl *c, int enabled); + +// TODO document +_UI_EXTERN void uiWindowsControlNotifyVisibilityChanged(uiWindowsControl *c); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/dep/libui/unix/OLD_table.c b/dep/libui/unix/OLD_table.c new file mode 100644 index 0000000..3774345 --- /dev/null +++ b/dep/libui/unix/OLD_table.c @@ -0,0 +1,406 @@ +// 26 june 2016 +#include "uipriv_unix.h" + +void *uiTableModelStrdup(const char *str) +{ + return g_strdup(str); +} + +void *uiTableModelGiveColor(double r, double g, double b, double a) +{ + GdkRGBA rgba; + + rgba.red = r; + rgba.green = g; + rgba.blue = b; + rgba.alpha = a; + return gdk_rgba_copy(&rgba); +} + +uiTableModel *uiNewTableModel(uiTableModelHandler *mh) +{ + uiTableModel *m; + + m = uiTableModel(g_object_new(uiTableModelType, NULL)); + m->mh = mh; + return m; +} + +void uiFreeTableModel(uiTableModel *m) +{ + g_object_unref(m); +} + +void uiTableModelRowInserted(uiTableModel *m, int newIndex) +{ + GtkTreePath *path; + GtkTreeIter iter; + + path = gtk_tree_path_new_from_indices(newIndex, -1); + iter.stamp = STAMP_GOOD; + iter.user_data = GINT_TO_POINTER(newIndex); + gtk_tree_model_row_inserted(GTK_TREE_MODEL(m), path, &iter); + gtk_tree_path_free(path); +} + +void uiTableModelRowChanged(uiTableModel *m, int index) +{ + GtkTreePath *path; + GtkTreeIter iter; + + path = gtk_tree_path_new_from_indices(index, -1); + iter.stamp = STAMP_GOOD; + iter.user_data = GINT_TO_POINTER(index); + gtk_tree_model_row_changed(GTK_TREE_MODEL(m), path, &iter); + gtk_tree_path_free(path); +} + +void uiTableModelRowDeleted(uiTableModel *m, int oldIndex) +{ + GtkTreePath *path; + + path = gtk_tree_path_new_from_indices(oldIndex, -1); + gtk_tree_model_row_deleted(GTK_TREE_MODEL(m), path); + gtk_tree_path_free(path); +} + +enum { + partText, + partImage, + partButton, + partCheckbox, + partProgressBar, +}; + +struct tablePart { + int type; + int textColumn; + int imageColumn; + int valueColumn; + int colorColumn; + GtkCellRenderer *r; + uiTable *tv; // for pixbufs and background color +}; + +struct uiTableColumn { + GtkTreeViewColumn *c; + uiTable *tv; // for pixbufs and background color + GPtrArray *parts; +}; + +struct uiTable { + uiUnixControl c; + GtkWidget *widget; + GtkContainer *scontainer; + GtkScrolledWindow *sw; + GtkWidget *treeWidget; + GtkTreeView *tv; + GPtrArray *columns; + uiTableModel *model; + int backgroundColumn; +}; + +// use the same size as GtkFileChooserWidget's treeview +// TODO refresh when icon theme changes +// TODO doesn't work when scaled +// TODO is this even necessary? +static void setImageSize(GtkCellRenderer *r) +{ + gint size; + gint width, height; + gint xpad, ypad; + + size = 16; // fallback used by GtkFileChooserWidget + if (gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &width, &height) != FALSE) + size = MAX(width, height); + gtk_cell_renderer_get_padding(r, &xpad, &ypad); + gtk_cell_renderer_set_fixed_size(r, + 2 * xpad + size, + 2 * ypad + size); +} + +static void applyColor(GtkTreeModel *mm, GtkTreeIter *iter, int modelColumn, GtkCellRenderer *r, const char *prop, const char *propSet) +{ + GValue value = G_VALUE_INIT; + GdkRGBA *rgba; + + gtk_tree_model_get_value(mm, iter, modelColumn, &value); + rgba = (GdkRGBA *) g_value_get_boxed(&value); + if (rgba != NULL) + g_object_set(r, prop, rgba, NULL); + else + g_object_set(r, propSet, FALSE, NULL); + g_value_unset(&value); +} + +static void dataFunc(GtkTreeViewColumn *c, GtkCellRenderer *r, GtkTreeModel *mm, GtkTreeIter *iter, gpointer data) +{ + struct tablePart *part = (struct tablePart *) data; + GValue value = G_VALUE_INIT; + const gchar *str; + uiImage *img; + int pval; + + switch (part->type) { + case partText: + gtk_tree_model_get_value(mm, iter, part->textColumn, &value); + str = g_value_get_string(&value); + g_object_set(r, "text", str, NULL); + if (part->colorColumn != -1) + applyColor(mm, iter, + part->colorColumn, + r, "foreground-rgba", "foreground-set"); + break; + case partImage: +//TODO setImageSize(r); + gtk_tree_model_get_value(mm, iter, part->imageColumn, &value); + img = (uiImage *) g_value_get_pointer(&value); + g_object_set(r, "surface", + uiprivImageAppropriateSurface(img, part->tv->treeWidget), + NULL); + break; + case partButton: + gtk_tree_model_get_value(mm, iter, part->textColumn, &value); + str = g_value_get_string(&value); + g_object_set(r, "text", str, NULL); + break; + case partCheckbox: + gtk_tree_model_get_value(mm, iter, part->valueColumn, &value); + g_object_set(r, "active", g_value_get_int(&value) != 0, NULL); + break; + case partProgressBar: + gtk_tree_model_get_value(mm, iter, part->valueColumn, &value); + pval = g_value_get_int(&value); + if (pval == -1) { + // TODO + } else + g_object_set(r, + "pulse", -1, + "value", pval, + NULL); + break; + } + g_value_unset(&value); + + if (part->tv->backgroundColumn != -1) + applyColor(mm, iter, + part->tv->backgroundColumn, + r, "cell-background-rgba", "cell-background-set"); +} + +static void onEdited(struct tablePart *part, int column, const char *pathstr, const void *data) +{ + GtkTreePath *path; + int row; + uiTableModel *m; + + path = gtk_tree_path_new_from_string(pathstr); + row = gtk_tree_path_get_indices(path)[0]; + gtk_tree_path_free(path); + m = part->tv->model; + (*(m->mh->SetCellValue))(m->mh, m, row, column, data); + // and update + uiTableModelRowChanged(m, row); +} + +static void appendPart(uiTableColumn *c, struct tablePart *part, GtkCellRenderer *r, int expand) +{ + part->r = r; + gtk_tree_view_column_pack_start(c->c, part->r, expand != 0); + gtk_tree_view_column_set_cell_data_func(c->c, part->r, dataFunc, part, NULL); + g_ptr_array_add(c->parts, part); +} + +static void textEdited(GtkCellRendererText *renderer, gchar *path, gchar *newText, gpointer data) +{ + struct tablePart *part = (struct tablePart *) data; + + onEdited(part, part->textColumn, path, newText); +} + +void uiTableColumnAppendTextPart(uiTableColumn *c, int modelColumn, int expand) +{ + struct tablePart *part; + GtkCellRenderer *r; + + part = uiprivNew(struct tablePart); + part->type = partText; + part->textColumn = modelColumn; + part->tv = c->tv; + part->colorColumn = -1; + + r = gtk_cell_renderer_text_new(); + g_object_set(r, "editable", FALSE, NULL); + g_signal_connect(r, "edited", G_CALLBACK(textEdited), part); + + appendPart(c, part, r, expand); +} + +void uiTableColumnAppendImagePart(uiTableColumn *c, int modelColumn, int expand) +{ + struct tablePart *part; + + part = uiprivNew(struct tablePart); + part->type = partImage; + part->imageColumn = modelColumn; + part->tv = c->tv; + appendPart(c, part, + gtk_cell_renderer_pixbuf_new(), + expand); +} + +// TODO wrong type here +static void buttonClicked(GtkCellRenderer *r, gchar *pathstr, gpointer data) +{ + struct tablePart *part = (struct tablePart *) data; + + onEdited(part, part->textColumn, pathstr, NULL); +} + +void uiTableColumnAppendButtonPart(uiTableColumn *c, int modelColumn, int expand) +{ + struct tablePart *part; + GtkCellRenderer *r; + + part = uiprivNew(struct tablePart); + part->type = partButton; + part->textColumn = modelColumn; + part->tv = c->tv; + + r = uiprivNewCellRendererButton(); + g_object_set(r, "sensitive", TRUE, NULL); // editable by default + g_signal_connect(r, "clicked", G_CALLBACK(buttonClicked), part); + + appendPart(c, part, r, expand); +} + +// yes, we need to do all this twice :| +static void checkboxToggled(GtkCellRendererToggle *r, gchar *pathstr, gpointer data) +{ + struct tablePart *part = (struct tablePart *) data; + GtkTreePath *path; + int row; + uiTableModel *m; + void *value; + int intval; + + path = gtk_tree_path_new_from_string(pathstr); + row = gtk_tree_path_get_indices(path)[0]; + gtk_tree_path_free(path); + m = part->tv->model; + value = (*(m->mh->CellValue))(m->mh, m, row, part->valueColumn); + intval = !uiTableModelTakeInt(value); + onEdited(part, part->valueColumn, pathstr, uiTableModelGiveInt(intval)); +} + +void uiTableColumnAppendCheckboxPart(uiTableColumn *c, int modelColumn, int expand) +{ + struct tablePart *part; + GtkCellRenderer *r; + + part = uiprivNew(struct tablePart); + part->type = partCheckbox; + part->valueColumn = modelColumn; + part->tv = c->tv; + + r = gtk_cell_renderer_toggle_new(); + g_object_set(r, "sensitive", TRUE, NULL); // editable by default + g_signal_connect(r, "toggled", G_CALLBACK(checkboxToggled), part); + + appendPart(c, part, r, expand); +} + +void uiTableColumnAppendProgressBarPart(uiTableColumn *c, int modelColumn, int expand) +{ + struct tablePart *part; + + part = uiprivNew(struct tablePart); + part->type = partProgressBar; + part->valueColumn = modelColumn; + part->tv = c->tv; + appendPart(c, part, + gtk_cell_renderer_progress_new(), + expand); +} + +void uiTableColumnPartSetEditable(uiTableColumn *c, int part, int editable) +{ + struct tablePart *p; + + p = (struct tablePart *) g_ptr_array_index(c->parts, part); + switch (p->type) { + case partImage: + case partProgressBar: + return; + case partButton: + case partCheckbox: + g_object_set(p->r, "sensitive", editable != 0, NULL); + return; + } + g_object_set(p->r, "editable", editable != 0, NULL); +} + +void uiTableColumnPartSetTextColor(uiTableColumn *c, int part, int modelColumn) +{ + struct tablePart *p; + + p = (struct tablePart *) g_ptr_array_index(c->parts, part); + p->colorColumn = modelColumn; + // TODO refresh table +} + +uiUnixControlAllDefaultsExceptDestroy(uiTable) + +static void uiTableDestroy(uiControl *c) +{ + uiTable *t = uiTable(c); + + // TODO + g_object_unref(t->widget); + uiFreeControl(uiControl(t)); +} + +uiTableColumn *uiTableAppendColumn(uiTable *t, const char *name) +{ + uiTableColumn *c; + + c = uiprivNew(uiTableColumn); + c->c = gtk_tree_view_column_new(); + gtk_tree_view_column_set_resizable(c->c, TRUE); + gtk_tree_view_column_set_title(c->c, name); + gtk_tree_view_append_column(t->tv, c->c); + c->tv = t; // TODO rename field to t, cascade + c->parts = g_ptr_array_new(); + return c; +} + +void uiTableSetRowBackgroundColorModelColumn(uiTable *t, int modelColumn) +{ + t->backgroundColumn = modelColumn; + // TODO refresh table +} + +uiTable *uiNewTable(uiTableModel *model) +{ + uiTable *t; + + uiUnixNewControl(uiTable, t); + + t->model = model; + t->backgroundColumn = -1; + + t->widget = gtk_scrolled_window_new(NULL, NULL); + t->scontainer = GTK_CONTAINER(t->widget); + t->sw = GTK_SCROLLED_WINDOW(t->widget); + gtk_scrolled_window_set_shadow_type(t->sw, GTK_SHADOW_IN); + + t->treeWidget = gtk_tree_view_new_with_model(GTK_TREE_MODEL(t->model)); + t->tv = GTK_TREE_VIEW(t->treeWidget); + // TODO set up t->tv + + gtk_container_add(t->scontainer, t->treeWidget); + // and make the tree view visible; only the scrolled window's visibility is controlled by libui + gtk_widget_show(t->treeWidget); + + return t; +} diff --git a/dep/libui/unix/alloc.c b/dep/libui/unix/alloc.c new file mode 100644 index 0000000..3fa0fd4 --- /dev/null +++ b/dep/libui/unix/alloc.c @@ -0,0 +1,84 @@ +// 7 april 2015 +#include +#include "uipriv_unix.h" + +static GPtrArray *allocations; + +#define UINT8(p) ((uint8_t *) (p)) +#define PVOID(p) ((void *) (p)) +#define EXTRA (sizeof (size_t) + sizeof (const char **)) +#define DATA(p) PVOID(UINT8(p) + EXTRA) +#define BASE(p) PVOID(UINT8(p) - EXTRA) +#define SIZE(p) ((size_t *) (p)) +#define CCHAR(p) ((const char **) (p)) +#define TYPE(p) CCHAR(UINT8(p) + sizeof (size_t)) + +void uiprivInitAlloc(void) +{ + allocations = g_ptr_array_new(); +} + +static void uninitComplain(gpointer ptr, gpointer data) +{ + char **str = (char **) data; + char *str2; + + if (*str == NULL) + *str = g_strdup_printf(""); + str2 = g_strdup_printf("%s%p %s\n", *str, ptr, *TYPE(ptr)); + g_free(*str); + *str = str2; +} + +void uiprivUninitAlloc(void) +{ + char *str = NULL; + + if (allocations->len == 0) { + g_ptr_array_free(allocations, TRUE); + return; + } + g_ptr_array_foreach(allocations, uninitComplain, &str); + uiprivUserBug("Some data was leaked; either you left a uiControl lying around or there's a bug in libui itself. Leaked data:\n%s", str); + g_free(str); +} + +void *uiprivAlloc(size_t size, const char *type) +{ + void *out; + + out = g_malloc0(EXTRA + size); + *SIZE(out) = size; + *TYPE(out) = type; + g_ptr_array_add(allocations, out); + return DATA(out); +} + +void *uiprivRealloc(void *p, size_t new, const char *type) +{ + void *out; + size_t *s; + + if (p == NULL) + return uiprivAlloc(new, type); + p = BASE(p); + out = g_realloc(p, EXTRA + new); + s = SIZE(out); + if (new > *s) + memset(((uint8_t *) DATA(out)) + *s, 0, new - *s); + *s = new; + if (g_ptr_array_remove(allocations, p) == FALSE) + uiprivImplBug("%p not found in allocations array in uiprivRealloc()", p); + g_ptr_array_add(allocations, out); + return DATA(out); +} + +void uiprivFree(void *p) +{ + if (p == NULL) + uiprivImplBug("attempt to uiprivFree(NULL)"); + p = BASE(p); + g_free(p); + if (g_ptr_array_remove(allocations, p) == FALSE) + uiprivImplBug("%p not found in allocations array in uiprivFree()", p); +} diff --git a/dep/libui/unix/area.c b/dep/libui/unix/area.c new file mode 100644 index 0000000..19b3463 --- /dev/null +++ b/dep/libui/unix/area.c @@ -0,0 +1,637 @@ +// 4 september 2015 +#include "uipriv_unix.h" + +// notes: +// - G_DECLARE_DERIVABLE/FINAL_INTERFACE() requires glib 2.44 and that's starting with debian stretch (testing) (GTK+ 3.18) and ubuntu 15.04 (GTK+ 3.14) - debian jessie has 2.42 (GTK+ 3.14) +#define areaWidgetType (areaWidget_get_type()) +#define areaWidget(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), areaWidgetType, areaWidget)) +#define isAreaWidget(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), areaWidgetType)) +#define areaWidgetClass(class) (G_TYPE_CHECK_CLASS_CAST((class), areaWidgetType, areaWidgetClass)) +#define isAreaWidgetClass(class) (G_TYPE_CHECK_CLASS_TYPE((class), areaWidget)) +#define getAreaWidgetClass(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), areaWidgetType, areaWidgetClass)) + +typedef struct areaWidget areaWidget; +typedef struct areaWidgetClass areaWidgetClass; + +struct areaWidget { + GtkDrawingArea parent_instance; + uiArea *a; + // construct-only parameters aare not set until after the init() function has returned + // we need this particular object available during init(), so put it here instead of in uiArea + // keep a pointer in uiArea for convenience, though + uiprivClickCounter cc; +}; + +struct areaWidgetClass { + GtkDrawingAreaClass parent_class; +}; + +struct uiArea { + uiUnixControl c; + GtkWidget *widget; // either swidget or areaWidget depending on whether it is scrolling + + GtkWidget *swidget; + GtkContainer *scontainer; + GtkScrolledWindow *sw; + + GtkWidget *areaWidget; + GtkDrawingArea *drawingArea; + areaWidget *area; + + uiAreaHandler *ah; + + gboolean scrolling; + int scrollWidth; + int scrollHeight; + + // note that this is a pointer; see above + uiprivClickCounter *cc; + + // for user window drags + GdkEventButton *dragevent; +}; + +G_DEFINE_TYPE(areaWidget, areaWidget, GTK_TYPE_DRAWING_AREA) + +static void areaWidget_init(areaWidget *aw) +{ + // for events + gtk_widget_add_events(GTK_WIDGET(aw), + GDK_POINTER_MOTION_MASK | + GDK_BUTTON_MOTION_MASK | + GDK_BUTTON_PRESS_MASK | + GDK_BUTTON_RELEASE_MASK | + GDK_KEY_PRESS_MASK | + GDK_KEY_RELEASE_MASK | + GDK_ENTER_NOTIFY_MASK | + GDK_LEAVE_NOTIFY_MASK); + + gtk_widget_set_can_focus(GTK_WIDGET(aw), TRUE); + + uiprivClickCounterReset(&(aw->cc)); +} + +static void areaWidget_dispose(GObject *obj) +{ + G_OBJECT_CLASS(areaWidget_parent_class)->dispose(obj); +} + +static void areaWidget_finalize(GObject *obj) +{ + G_OBJECT_CLASS(areaWidget_parent_class)->finalize(obj); +} + +static void areaWidget_size_allocate(GtkWidget *w, GtkAllocation *allocation) +{ + areaWidget *aw = areaWidget(w); + uiArea *a = aw->a; + + // GtkDrawingArea has a size_allocate() implementation; we need to call it + // this will call gtk_widget_set_allocation() for us + GTK_WIDGET_CLASS(areaWidget_parent_class)->size_allocate(w, allocation); + + if (!a->scrolling) + // we must redraw everything on resize because Windows requires it + // TODO https://developer.gnome.org/gtk3/3.10/GtkWidget.html#gtk-widget-set-redraw-on-allocate ? + // TODO drop this rule; it was stupid and documenting this was stupid — let platforms where it matters do it on their own + // TODO or do we not, for parity of performance? + gtk_widget_queue_resize(w); +} + +static void loadAreaSize(uiArea *a, double *width, double *height) +{ + GtkAllocation allocation; + + *width = 0; + *height = 0; + // don't provide size information for scrolling areas + if (!a->scrolling) { + gtk_widget_get_allocation(a->areaWidget, &allocation); + // these are already in drawing space coordinates + // for drawing, the size of drawing space has the same value as the widget allocation + // thanks to tristan in irc.gimp.net/#gtk+ + *width = allocation.width; + *height = allocation.height; + } +} + +static gboolean areaWidget_draw(GtkWidget *w, cairo_t *cr) +{ + areaWidget *aw = areaWidget(w); + uiArea *a = aw->a; + uiAreaDrawParams dp; + double clipX0, clipY0, clipX1, clipY1; + + dp.Context = uiprivNewContext(cr, + gtk_widget_get_style_context(a->widget)); + + loadAreaSize(a, &(dp.AreaWidth), &(dp.AreaHeight)); + + cairo_clip_extents(cr, &clipX0, &clipY0, &clipX1, &clipY1); + dp.ClipX = clipX0; + dp.ClipY = clipY0; + dp.ClipWidth = clipX1 - clipX0; + dp.ClipHeight = clipY1 - clipY0; + + // no need to save or restore the graphics state to reset transformations; GTK+ does that for us + (*(a->ah->Draw))(a->ah, a, &dp); + + uiprivFreeContext(dp.Context); + return FALSE; +} + +// to do this properly for scrolling areas, we need to +// - return the same value for min and nat +// - call gtk_widget_queue_resize() when the size changes +// thanks to Company in irc.gimp.net/#gtk+ +static void areaWidget_get_preferred_height(GtkWidget *w, gint *min, gint *nat) +{ + areaWidget *aw = areaWidget(w); + uiArea *a = aw->a; + + // always chain up just in case + GTK_WIDGET_CLASS(areaWidget_parent_class)->get_preferred_height(w, min, nat); + if (a->scrolling) { + *min = a->scrollHeight; + *nat = a->scrollHeight; + } +} + +static void areaWidget_get_preferred_width(GtkWidget *w, gint *min, gint *nat) +{ + areaWidget *aw = areaWidget(w); + uiArea *a = aw->a; + + // always chain up just in case + GTK_WIDGET_CLASS(areaWidget_parent_class)->get_preferred_width(w, min, nat); + if (a->scrolling) { + *min = a->scrollWidth; + *nat = a->scrollWidth; + } +} + +static guint translateModifiers(guint state, GdkWindow *window) +{ + GdkModifierType statetype; + + // GDK doesn't initialize the modifier flags fully; we have to explicitly tell it to (thanks to Daniel_S and daniels (two different people) in irc.gimp.net/#gtk+) + statetype = state; + gdk_keymap_add_virtual_modifiers( + gdk_keymap_get_for_display(gdk_window_get_display(window)), + &statetype); + return statetype; +} + +static uiModifiers toModifiers(guint state) +{ + uiModifiers m; + + m = 0; + if ((state & GDK_CONTROL_MASK) != 0) + m |= uiModifierCtrl; + if ((state & GDK_META_MASK) != 0) + m |= uiModifierAlt; + if ((state & GDK_MOD1_MASK) != 0) // GTK+ itself requires this to be Alt (just read through gtkaccelgroup.c) + m |= uiModifierAlt; + if ((state & GDK_SHIFT_MASK) != 0) + m |= uiModifierShift; + if ((state & GDK_SUPER_MASK) != 0) + m |= uiModifierSuper; + return m; +} + +// capture on drag is done automatically on GTK+ +static void finishMouseEvent(uiArea *a, uiAreaMouseEvent *me, guint mb, gdouble x, gdouble y, guint state, GdkWindow *window) +{ + // on GTK+, mouse buttons 4-7 are for scrolling; if we got here, that's a mistake + if (mb >= 4 && mb <= 7) + return; + // if the button ID >= 8, continue counting from 4, as in the MouseEvent spec + if (me->Down >= 8) + me->Down -= 4; + if (me->Up >= 8) + me->Up -= 4; + + state = translateModifiers(state, window); + me->Modifiers = toModifiers(state); + + // the mb != # checks exclude the Up/Down button from Held + me->Held1To64 = 0; + if (mb != 1 && (state & GDK_BUTTON1_MASK) != 0) + me->Held1To64 |= 1 << 0; + if (mb != 2 && (state & GDK_BUTTON2_MASK) != 0) + me->Held1To64 |= 1 << 1; + if (mb != 3 && (state & GDK_BUTTON3_MASK) != 0) + me->Held1To64 |= 1 << 2; + // don't check GDK_BUTTON4_MASK or GDK_BUTTON5_MASK because those are for the scrolling buttons mentioned above + // GDK expressly does not support any more buttons in the GdkModifierType; see https://git.gnome.org/browse/gtk+/tree/gdk/x11/gdkdevice-xi2.c#n763 (thanks mclasen in irc.gimp.net/#gtk+) + + // these are already in drawing space coordinates + // the size of drawing space has the same value as the widget allocation + // thanks to tristan in irc.gimp.net/#gtk+ + me->X = x; + me->Y = y; + + loadAreaSize(a, &(me->AreaWidth), &(me->AreaHeight)); + + (*(a->ah->MouseEvent))(a->ah, a, me); +} + +static gboolean areaWidget_button_press_event(GtkWidget *w, GdkEventButton *e) +{ + areaWidget *aw = areaWidget(w); + uiArea *a = aw->a; + gint maxTime, maxDistance; + GtkSettings *settings; + uiAreaMouseEvent me; + + // clicking doesn't automatically transfer keyboard focus; we must do so manually (thanks tristan in irc.gimp.net/#gtk+) + gtk_widget_grab_focus(w); + + me.Down = e->button; + me.Up = 0; + + // we handle multiple clicks ourselves here, in the same way as we do on Windows + if (e->type != GDK_BUTTON_PRESS) + // ignore GDK's generated double-clicks and beyond + return GDK_EVENT_PROPAGATE; + settings = gtk_widget_get_settings(w); + g_object_get(settings, + "gtk-double-click-time", &maxTime, + "gtk-double-click-distance", &maxDistance, + NULL); + // don't unref settings; it's transfer-none (thanks gregier in irc.gimp.net/#gtk+) + // e->time is guint32 + // e->x and e->y are floating-point; just make them 32-bit integers + // maxTime and maxDistance... are gint, which *should* fit, hopefully... + me.Count = uiprivClickCounterClick(a->cc, me.Down, + e->x, e->y, + e->time, maxTime, + maxDistance, maxDistance); + + // and set things up for window drags + a->dragevent = e; + finishMouseEvent(a, &me, e->button, e->x, e->y, e->state, e->window); + a->dragevent = NULL; + return GDK_EVENT_PROPAGATE; +} + +static gboolean areaWidget_button_release_event(GtkWidget *w, GdkEventButton *e) +{ + areaWidget *aw = areaWidget(w); + uiArea *a = aw->a; + uiAreaMouseEvent me; + + me.Down = 0; + me.Up = e->button; + me.Count = 0; + finishMouseEvent(a, &me, e->button, e->x, e->y, e->state, e->window); + return GDK_EVENT_PROPAGATE; +} + +static gboolean areaWidget_motion_notify_event(GtkWidget *w, GdkEventMotion *e) +{ + areaWidget *aw = areaWidget(w); + uiArea *a = aw->a; + uiAreaMouseEvent me; + + me.Down = 0; + me.Up = 0; + me.Count = 0; + finishMouseEvent(a, &me, 0, e->x, e->y, e->state, e->window); + return GDK_EVENT_PROPAGATE; +} + +// we want switching away from the control to reset the double-click counter, like with WM_ACTIVATE on Windows +// according to tristan in irc.gimp.net/#gtk+, doing this on both enter-notify-event and leave-notify-event is correct (and it seems to be true in my own tests; plus the events DO get sent when switching programs with the keyboard (just pointing that out)) +static gboolean onCrossing(areaWidget *aw, int left) +{ + uiArea *a = aw->a; + + (*(a->ah->MouseCrossed))(a->ah, a, left); + uiprivClickCounterReset(a->cc); + return GDK_EVENT_PROPAGATE; +} + +static gboolean areaWidget_enter_notify_event(GtkWidget *w, GdkEventCrossing *e) +{ + return onCrossing(areaWidget(w), 0); +} + +static gboolean areaWidget_leave_notify_event(GtkWidget *w, GdkEventCrossing *e) +{ + return onCrossing(areaWidget(w), 1); +} + +// note: there is no equivalent to WM_CAPTURECHANGED on GTK+; there literally is no way to break a grab like that (at least not on X11 and Wayland) +// even if I invoke the task switcher and switch processes, the mouse grab will still be held until I let go of all buttons +// therefore, no DragBroken() + +// we use GDK_KEY_Print as a sentinel because libui will never support the print screen key; that key belongs to the user + +static const struct { + guint keyval; + uiExtKey extkey; +} extKeys[] = { + { GDK_KEY_Escape, uiExtKeyEscape }, + { GDK_KEY_Insert, uiExtKeyInsert }, + { GDK_KEY_Delete, uiExtKeyDelete }, + { GDK_KEY_Home, uiExtKeyHome }, + { GDK_KEY_End, uiExtKeyEnd }, + { GDK_KEY_Page_Up, uiExtKeyPageUp }, + { GDK_KEY_Page_Down, uiExtKeyPageDown }, + { GDK_KEY_Up, uiExtKeyUp }, + { GDK_KEY_Down, uiExtKeyDown }, + { GDK_KEY_Left, uiExtKeyLeft }, + { GDK_KEY_Right, uiExtKeyRight }, + { GDK_KEY_F1, uiExtKeyF1 }, + { GDK_KEY_F2, uiExtKeyF2 }, + { GDK_KEY_F3, uiExtKeyF3 }, + { GDK_KEY_F4, uiExtKeyF4 }, + { GDK_KEY_F5, uiExtKeyF5 }, + { GDK_KEY_F6, uiExtKeyF6 }, + { GDK_KEY_F7, uiExtKeyF7 }, + { GDK_KEY_F8, uiExtKeyF8 }, + { GDK_KEY_F9, uiExtKeyF9 }, + { GDK_KEY_F10, uiExtKeyF10 }, + { GDK_KEY_F11, uiExtKeyF11 }, + { GDK_KEY_F12, uiExtKeyF12 }, + // numpad numeric keys and . are handled in events.c + { GDK_KEY_KP_Enter, uiExtKeyNEnter }, + { GDK_KEY_KP_Add, uiExtKeyNAdd }, + { GDK_KEY_KP_Subtract, uiExtKeyNSubtract }, + { GDK_KEY_KP_Multiply, uiExtKeyNMultiply }, + { GDK_KEY_KP_Divide, uiExtKeyNDivide }, + { GDK_KEY_Print, 0 }, +}; + +static const struct { + guint keyval; + uiModifiers mod; +} modKeys[] = { + { GDK_KEY_Control_L, uiModifierCtrl }, + { GDK_KEY_Control_R, uiModifierCtrl }, + { GDK_KEY_Alt_L, uiModifierAlt }, + { GDK_KEY_Alt_R, uiModifierAlt }, + { GDK_KEY_Meta_L, uiModifierAlt }, + { GDK_KEY_Meta_R, uiModifierAlt }, + { GDK_KEY_Shift_L, uiModifierShift }, + { GDK_KEY_Shift_R, uiModifierShift }, + { GDK_KEY_Super_L, uiModifierSuper }, + { GDK_KEY_Super_R, uiModifierSuper }, + { GDK_KEY_Print, 0 }, +}; + +static int areaKeyEvent(uiArea *a, int up, GdkEventKey *e) +{ + uiAreaKeyEvent ke; + guint state; + int i; + + ke.Key = 0; + ke.ExtKey = 0; + ke.Modifier = 0; + + state = translateModifiers(e->state, e->window); + ke.Modifiers = toModifiers(state); + + ke.Up = up; + + for (i = 0; extKeys[i].keyval != GDK_KEY_Print; i++) + if (extKeys[i].keyval == e->keyval) { + ke.ExtKey = extKeys[i].extkey; + goto keyFound; + } + + for (i = 0; modKeys[i].keyval != GDK_KEY_Print; i++) + if (modKeys[i].keyval == e->keyval) { + ke.Modifier = modKeys[i].mod; + // don't include the modifier in ke.Modifiers + ke.Modifiers &= ~ke.Modifier; + goto keyFound; + } + + if (uiprivFromScancode(e->hardware_keycode - 8, &ke)) + goto keyFound; + + // no supported key found; treat as unhandled + return 0; + +keyFound: + return (*(a->ah->KeyEvent))(a->ah, a, &ke); +} + +static gboolean areaWidget_key_press_event(GtkWidget *w, GdkEventKey *e) +{ + areaWidget *aw = areaWidget(w); + uiArea *a = aw->a; + + if (areaKeyEvent(a, 0, e)) + return GDK_EVENT_STOP; + return GDK_EVENT_PROPAGATE; +} + +static gboolean areaWidget_key_release_event(GtkWidget *w, GdkEventKey *e) +{ + areaWidget *aw = areaWidget(w); + uiArea *a = aw->a; + + if (areaKeyEvent(a, 1, e)) + return GDK_EVENT_STOP; + return GDK_EVENT_PROPAGATE; +} + +enum { + pArea = 1, + nProps, +}; + +static GParamSpec *pspecArea; + +static void areaWidget_set_property(GObject *obj, guint prop, const GValue *value, GParamSpec *pspec) +{ + areaWidget *aw = areaWidget(obj); + + switch (prop) { + case pArea: + aw->a = (uiArea *) g_value_get_pointer(value); + aw->a->cc = &(aw->cc); + return; + } + G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, prop, pspec); +} + +static void areaWidget_get_property(GObject *obj, guint prop, GValue *value, GParamSpec *pspec) +{ + G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, prop, pspec); +} + +static void areaWidget_class_init(areaWidgetClass *class) +{ + G_OBJECT_CLASS(class)->dispose = areaWidget_dispose; + G_OBJECT_CLASS(class)->finalize = areaWidget_finalize; + G_OBJECT_CLASS(class)->set_property = areaWidget_set_property; + G_OBJECT_CLASS(class)->get_property = areaWidget_get_property; + + GTK_WIDGET_CLASS(class)->size_allocate = areaWidget_size_allocate; + GTK_WIDGET_CLASS(class)->draw = areaWidget_draw; + GTK_WIDGET_CLASS(class)->get_preferred_height = areaWidget_get_preferred_height; + GTK_WIDGET_CLASS(class)->get_preferred_width = areaWidget_get_preferred_width; + GTK_WIDGET_CLASS(class)->button_press_event = areaWidget_button_press_event; + GTK_WIDGET_CLASS(class)->button_release_event = areaWidget_button_release_event; + GTK_WIDGET_CLASS(class)->motion_notify_event = areaWidget_motion_notify_event; + GTK_WIDGET_CLASS(class)->enter_notify_event = areaWidget_enter_notify_event; + GTK_WIDGET_CLASS(class)->leave_notify_event = areaWidget_leave_notify_event; + GTK_WIDGET_CLASS(class)->key_press_event = areaWidget_key_press_event; + GTK_WIDGET_CLASS(class)->key_release_event = areaWidget_key_release_event; + + pspecArea = g_param_spec_pointer("libui-area", + "libui-area", + "uiArea.", + G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS); + g_object_class_install_property(G_OBJECT_CLASS(class), pArea, pspecArea); +} + +// control implementation + +uiUnixControlAllDefaults(uiArea) + +void uiAreaSetSize(uiArea *a, int width, int height) +{ + if (!a->scrolling) + uiprivUserBug("You cannot call uiAreaSetSize() on a non-scrolling uiArea. (area: %p)", a); + a->scrollWidth = width; + a->scrollHeight = height; + gtk_widget_queue_resize(a->areaWidget); +} + +void uiAreaQueueRedrawAll(uiArea *a) +{ + gtk_widget_queue_draw(a->areaWidget); +} + +void uiAreaScrollTo(uiArea *a, double x, double y, double width, double height) +{ + // TODO + // TODO adjust adjustments and find source for that +} + +void uiAreaBeginUserWindowMove(uiArea *a) +{ + GtkWidget *toplevel; + + if (a->dragevent == NULL) + uiprivUserBug("cannot call uiAreaBeginUserWindowMove() outside of a Mouse() with Down != 0"); + // TODO don't we have a libui function for this? did I scrap it? + // TODO widget or areaWidget? + toplevel = gtk_widget_get_toplevel(a->widget); + if (toplevel == NULL) { + // TODO + return; + } + // the docs say to do this + if (!gtk_widget_is_toplevel(toplevel)) { + // TODO + return; + } + if (!GTK_IS_WINDOW(toplevel)) { + // TODO + return; + } + gtk_window_begin_move_drag(GTK_WINDOW(toplevel), + a->dragevent->button, + a->dragevent->x_root, // TODO are these correct? + a->dragevent->y_root, + a->dragevent->time); +} + +static const GdkWindowEdge edges[] = { + [uiWindowResizeEdgeLeft] = GDK_WINDOW_EDGE_WEST, + [uiWindowResizeEdgeTop] = GDK_WINDOW_EDGE_NORTH, + [uiWindowResizeEdgeRight] = GDK_WINDOW_EDGE_EAST, + [uiWindowResizeEdgeBottom] = GDK_WINDOW_EDGE_SOUTH, + [uiWindowResizeEdgeTopLeft] = GDK_WINDOW_EDGE_NORTH_WEST, + [uiWindowResizeEdgeTopRight] = GDK_WINDOW_EDGE_NORTH_EAST, + [uiWindowResizeEdgeBottomLeft] = GDK_WINDOW_EDGE_SOUTH_WEST, + [uiWindowResizeEdgeBottomRight] = GDK_WINDOW_EDGE_SOUTH_EAST, +}; + +void uiAreaBeginUserWindowResize(uiArea *a, uiWindowResizeEdge edge) +{ + GtkWidget *toplevel; + + if (a->dragevent == NULL) + uiprivUserBug("cannot call uiAreaBeginUserWindowResize() outside of a Mouse() with Down != 0"); + // TODO don't we have a libui function for this? did I scrap it? + // TODO widget or areaWidget? + toplevel = gtk_widget_get_toplevel(a->widget); + if (toplevel == NULL) { + // TODO + return; + } + // the docs say to do this + if (!gtk_widget_is_toplevel(toplevel)) { + // TODO + return; + } + if (!GTK_IS_WINDOW(toplevel)) { + // TODO + return; + } + gtk_window_begin_resize_drag(GTK_WINDOW(toplevel), + edges[edge], + a->dragevent->button, + a->dragevent->x_root, // TODO are these correct? + a->dragevent->y_root, + a->dragevent->time); +} + +uiArea *uiNewArea(uiAreaHandler *ah) +{ + uiArea *a; + + uiUnixNewControl(uiArea, a); + + a->ah = ah; + a->scrolling = FALSE; + + a->areaWidget = GTK_WIDGET(g_object_new(areaWidgetType, + "libui-area", a, + NULL)); + a->drawingArea = GTK_DRAWING_AREA(a->areaWidget); + a->area = areaWidget(a->areaWidget); + + a->widget = a->areaWidget; + + return a; +} + +uiArea *uiNewScrollingArea(uiAreaHandler *ah, int width, int height) +{ + uiArea *a; + + uiUnixNewControl(uiArea, a); + + a->ah = ah; + a->scrolling = TRUE; + a->scrollWidth = width; + a->scrollHeight = height; + + a->swidget = gtk_scrolled_window_new(NULL, NULL); + a->scontainer = GTK_CONTAINER(a->swidget); + a->sw = GTK_SCROLLED_WINDOW(a->swidget); + + a->areaWidget = GTK_WIDGET(g_object_new(areaWidgetType, + "libui-area", a, + NULL)); + a->drawingArea = GTK_DRAWING_AREA(a->areaWidget); + a->area = areaWidget(a->areaWidget); + + a->widget = a->swidget; + + gtk_container_add(a->scontainer, a->areaWidget); + // and make the area visible; only the scrolled window's visibility is controlled by libui + gtk_widget_show(a->areaWidget); + + return a; +} diff --git a/dep/libui/unix/attrstr.c b/dep/libui/unix/attrstr.c new file mode 100644 index 0000000..f543943 --- /dev/null +++ b/dep/libui/unix/attrstr.c @@ -0,0 +1,145 @@ +// 12 february 2017 +#include "uipriv_unix.h" +#include "attrstr.h" + +// TODO pango alpha attributes turn 0 into 65535 :| + +// TODO make this name less generic? +struct foreachParams { + PangoAttrList *attrs; +}; + +static void addattr(struct foreachParams *p, size_t start, size_t end, PangoAttribute *attr) +{ + if (attr == NULL) // in case of a future attribute + return; + attr->start_index = start; + attr->end_index = end; + pango_attr_list_insert(p->attrs, attr); +} + +static uiForEach processAttribute(const uiAttributedString *s, const uiAttribute *attr, size_t start, size_t end, void *data) +{ + struct foreachParams *p = (struct foreachParams *) data; + double r, g, b, a; + PangoUnderline underline; + uiUnderlineColor colorType; + const uiOpenTypeFeatures *features; + GString *featurestr; + + switch (uiAttributeGetType(attr)) { + case uiAttributeTypeFamily: + addattr(p, start, end, + pango_attr_family_new(uiAttributeFamily(attr))); + break; + case uiAttributeTypeSize: + addattr(p, start, end, + pango_attr_size_new(cairoToPango(uiAttributeSize(attr)))); + break; + case uiAttributeTypeWeight: + // TODO reverse the misalignment from drawtext.c if it is corrected + addattr(p, start, end, + pango_attr_weight_new(uiprivWeightToPangoWeight(uiAttributeWeight(attr)))); + break; + case uiAttributeTypeItalic: + addattr(p, start, end, + pango_attr_style_new(uiprivItalicToPangoStyle(uiAttributeItalic(attr)))); + break; + case uiAttributeTypeStretch: + addattr(p, start, end, + pango_attr_stretch_new(uiprivStretchToPangoStretch(uiAttributeStretch(attr)))); + break; + case uiAttributeTypeColor: + uiAttributeColor(attr, &r, &g, &b, &a); + addattr(p, start, end, + pango_attr_foreground_new( + (guint16) (r * 65535.0), + (guint16) (g * 65535.0), + (guint16) (b * 65535.0))); + addattr(p, start, end, + uiprivFUTURE_pango_attr_foreground_alpha_new( + (guint16) (a * 65535.0))); + break; + case uiAttributeTypeBackground: + // TODO make sure this works properly with line paragraph spacings (after figuring out what that means, of course) + uiAttributeColor(attr, &r, &g, &b, &a); + addattr(p, start, end, + pango_attr_background_new( + (guint16) (r * 65535.0), + (guint16) (g * 65535.0), + (guint16) (b * 65535.0))); + addattr(p, start, end, + uiprivFUTURE_pango_attr_background_alpha_new( + (guint16) (a * 65535.0))); + break; + case uiAttributeTypeUnderline: + switch (uiAttributeUnderline(attr)) { + case uiUnderlineNone: + underline = PANGO_UNDERLINE_NONE; + break; + case uiUnderlineSingle: + underline = PANGO_UNDERLINE_SINGLE; + break; + case uiUnderlineDouble: + underline = PANGO_UNDERLINE_DOUBLE; + break; + case uiUnderlineSuggestion: + underline = PANGO_UNDERLINE_ERROR; + break; + } + addattr(p, start, end, + pango_attr_underline_new(underline)); + break; + case uiAttributeTypeUnderlineColor: + uiAttributeUnderlineColor(attr, &colorType, &r, &g, &b, &a); + switch (colorType) { + case uiUnderlineColorCustom: + addattr(p, start, end, + pango_attr_underline_color_new( + (guint16) (r * 65535.0), + (guint16) (g * 65535.0), + (guint16) (b * 65535.0))); + break; + case uiUnderlineColorSpelling: + // TODO GtkTextView style property error-underline-color + addattr(p, start, end, + pango_attr_underline_color_new(65535, 0, 0)); + break; + case uiUnderlineColorGrammar: + // TODO find a more appropriate color + addattr(p, start, end, + pango_attr_underline_color_new(0, 65535, 0)); + break; + case uiUnderlineColorAuxiliary: + // TODO find a more appropriate color + addattr(p, start, end, + pango_attr_underline_color_new(0, 0, 65535)); + break; + } + break; + case uiAttributeTypeFeatures: + // only generate an attribute if the features object is not NULL + // TODO state that this is allowed + features = uiAttributeFeatures(attr); + if (features == NULL) + break; + featurestr = uiprivOpenTypeFeaturesToPangoCSSFeaturesString(features); + addattr(p, start, end, + uiprivFUTURE_pango_attr_font_features_new(featurestr->str)); + g_string_free(featurestr, TRUE); + break; + default: + // TODO complain + ; + } + return uiForEachContinue; +} + +PangoAttrList *uiprivAttributedStringToPangoAttrList(uiDrawTextLayoutParams *p) +{ + struct foreachParams fep; + + fep.attrs = pango_attr_list_new(); + uiAttributedStringForEachAttribute(p->String, processAttribute, &fep); + return fep.attrs; +} diff --git a/dep/libui/unix/attrstr.h b/dep/libui/unix/attrstr.h new file mode 100644 index 0000000..984ac1f --- /dev/null +++ b/dep/libui/unix/attrstr.h @@ -0,0 +1,20 @@ +// 11 march 2018 +#include "../common/attrstr.h" + +// See https://developer.gnome.org/pango/1.30/pango-Cairo-Rendering.html#pango-Cairo-Rendering.description +// For the conversion, see https://developer.gnome.org/pango/1.30/pango-Glyph-Storage.html#pango-units-to-double and https://developer.gnome.org/pango/1.30/pango-Glyph-Storage.html#pango-units-from-double +#define pangoToCairo(pango) (pango_units_to_double(pango)) +#define cairoToPango(cairo) (pango_units_from_double(cairo)) + +// opentype.c +extern GString *uiprivOpenTypeFeaturesToPangoCSSFeaturesString(const uiOpenTypeFeatures *otf); + +// fontmatch.c +extern PangoWeight uiprivWeightToPangoWeight(uiTextWeight w); +extern PangoStyle uiprivItalicToPangoStyle(uiTextItalic i); +extern PangoStretch uiprivStretchToPangoStretch(uiTextStretch s); +extern PangoFontDescription *uiprivFontDescriptorToPangoFontDescription(const uiFontDescriptor *uidesc); +extern void uiprivFontDescriptorFromPangoFontDescription(PangoFontDescription *pdesc, uiFontDescriptor *uidesc); + +// attrstr.c +extern PangoAttrList *uiprivAttributedStringToPangoAttrList(uiDrawTextLayoutParams *p); diff --git a/dep/libui/unix/box.c b/dep/libui/unix/box.c new file mode 100644 index 0000000..82cf2dd --- /dev/null +++ b/dep/libui/unix/box.c @@ -0,0 +1,159 @@ +// 7 april 2015 +#include "uipriv_unix.h" + +struct boxChild { + uiControl *c; + int stretchy; + gboolean oldhexpand; + GtkAlign oldhalign; + gboolean oldvexpand; + GtkAlign oldvalign; +}; + +struct uiBox { + uiUnixControl c; + GtkWidget *widget; + GtkContainer *container; + GtkBox *box; + GArray *controls; + int vertical; + int padded; + GtkSizeGroup *stretchygroup; // ensures all stretchy controls have the same size +}; + +uiUnixControlAllDefaultsExceptDestroy(uiBox) + +#define ctrl(b, i) &g_array_index(b->controls, struct boxChild, i) + +static void uiBoxDestroy(uiControl *c) +{ + uiBox *b = uiBox(c); + struct boxChild *bc; + guint i; + + // kill the size group + g_object_unref(b->stretchygroup); + // free all controls + for (i = 0; i < b->controls->len; i++) { + bc = ctrl(b, i); + uiControlSetParent(bc->c, NULL); + // and make sure the widget itself stays alive + uiUnixControlSetContainer(uiUnixControl(bc->c), b->container, TRUE); + uiControlDestroy(bc->c); + } + g_array_free(b->controls, TRUE); + // and then ourselves + g_object_unref(b->widget); + uiFreeControl(uiControl(b)); +} + +void uiBoxAppend(uiBox *b, uiControl *c, int stretchy) +{ + struct boxChild bc; + GtkWidget *widget; + + bc.c = c; + bc.stretchy = stretchy; + widget = GTK_WIDGET(uiControlHandle(bc.c)); + bc.oldhexpand = gtk_widget_get_hexpand(widget); + bc.oldhalign = gtk_widget_get_halign(widget); + bc.oldvexpand = gtk_widget_get_vexpand(widget); + bc.oldvalign = gtk_widget_get_valign(widget); + + if (bc.stretchy) { + if (b->vertical) { + gtk_widget_set_vexpand(widget, TRUE); + gtk_widget_set_valign(widget, GTK_ALIGN_FILL); + } else { + gtk_widget_set_hexpand(widget, TRUE); + gtk_widget_set_halign(widget, GTK_ALIGN_FILL); + } + gtk_size_group_add_widget(b->stretchygroup, widget); + } else + if (b->vertical) + gtk_widget_set_vexpand(widget, FALSE); + else + gtk_widget_set_hexpand(widget, FALSE); + // and make them fill the opposite direction + if (b->vertical) { + gtk_widget_set_hexpand(widget, TRUE); + gtk_widget_set_halign(widget, GTK_ALIGN_FILL); + } else { + gtk_widget_set_vexpand(widget, TRUE); + gtk_widget_set_valign(widget, GTK_ALIGN_FILL); + } + + uiControlSetParent(bc.c, uiControl(b)); + uiUnixControlSetContainer(uiUnixControl(bc.c), b->container, FALSE); + g_array_append_val(b->controls, bc); +} + +void uiBoxDelete(uiBox *b, int index) +{ + struct boxChild *bc; + GtkWidget *widget; + + bc = ctrl(b, index); + widget = GTK_WIDGET(uiControlHandle(bc->c)); + + uiControlSetParent(bc->c, NULL); + uiUnixControlSetContainer(uiUnixControl(bc->c), b->container, TRUE); + + if (bc->stretchy) + gtk_size_group_remove_widget(b->stretchygroup, widget); + gtk_widget_set_hexpand(widget, bc->oldhexpand); + gtk_widget_set_halign(widget, bc->oldhalign); + gtk_widget_set_vexpand(widget, bc->oldvexpand); + gtk_widget_set_valign(widget, bc->oldvalign); + + g_array_remove_index(b->controls, index); +} + +int uiBoxPadded(uiBox *b) +{ + return b->padded; +} + +void uiBoxSetPadded(uiBox *b, int padded) +{ + b->padded = padded; + if (b->padded) + if (b->vertical) + gtk_box_set_spacing(b->box, uiprivGTKYPadding); + else + gtk_box_set_spacing(b->box, uiprivGTKXPadding); + else + gtk_box_set_spacing(b->box, 0); +} + +static uiBox *finishNewBox(GtkOrientation orientation) +{ + uiBox *b; + + uiUnixNewControl(uiBox, b); + + b->widget = gtk_box_new(orientation, 0); + b->container = GTK_CONTAINER(b->widget); + b->box = GTK_BOX(b->widget); + + b->vertical = orientation == GTK_ORIENTATION_VERTICAL; + + if (b->vertical) + b->stretchygroup = gtk_size_group_new(GTK_SIZE_GROUP_VERTICAL); + else + b->stretchygroup = gtk_size_group_new(GTK_SIZE_GROUP_HORIZONTAL); + + b->controls = g_array_new(FALSE, TRUE, sizeof (struct boxChild)); + + return b; +} + +uiBox *uiNewHorizontalBox(void) +{ + return finishNewBox(GTK_ORIENTATION_HORIZONTAL); +} + +uiBox *uiNewVerticalBox(void) +{ + return finishNewBox(GTK_ORIENTATION_VERTICAL); +} diff --git a/dep/libui/unix/button.c b/dep/libui/unix/button.c new file mode 100644 index 0000000..00a87f4 --- /dev/null +++ b/dep/libui/unix/button.c @@ -0,0 +1,55 @@ +// 10 june 2015 +#include "uipriv_unix.h" + +struct uiButton { + uiUnixControl c; + GtkWidget *widget; + GtkButton *button; + void (*onClicked)(uiButton *, void *); + void *onClickedData; +}; + +uiUnixControlAllDefaults(uiButton) + +static void onClicked(GtkButton *button, gpointer data) +{ + uiButton *b = uiButton(data); + + (*(b->onClicked))(b, b->onClickedData); +} + +static void defaultOnClicked(uiButton *b, void *data) +{ + // do nothing +} + +char *uiButtonText(uiButton *b) +{ + return uiUnixStrdupText(gtk_button_get_label(b->button)); +} + +void uiButtonSetText(uiButton *b, const char *text) +{ + gtk_button_set_label(b->button, text); +} + +void uiButtonOnClicked(uiButton *b, void (*f)(uiButton *, void *), void *data) +{ + b->onClicked = f; + b->onClickedData = data; +} + +uiButton *uiNewButton(const char *text) +{ + uiButton *b; + + uiUnixNewControl(uiButton, b); + + b->widget = gtk_button_new_with_label(text); + b->button = GTK_BUTTON(b->widget); + + g_signal_connect(b->widget, "clicked", G_CALLBACK(onClicked), b); + uiButtonOnClicked(b, defaultOnClicked, NULL); + + return b; +} diff --git a/dep/libui/unix/cellrendererbutton.c b/dep/libui/unix/cellrendererbutton.c new file mode 100644 index 0000000..608cd61 --- /dev/null +++ b/dep/libui/unix/cellrendererbutton.c @@ -0,0 +1,332 @@ +// 28 june 2016 +#include "uipriv_unix.h" + +// TODOs +// - it's a rather tight fit +// - selected row text color is white (TODO not on 3.22) +// - accessibility +// - right side too big? (TODO reverify) + +#define cellRendererButtonType (cellRendererButton_get_type()) +#define cellRendererButton(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), cellRendererButtonType, cellRendererButton)) +#define isCellRendererButton(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), cellRendererButtonType)) +#define cellRendererButtonClass(class) (G_TYPE_CHECK_CLASS_CAST((class), cellRendererButtonType, cellRendererButtonClass)) +#define isCellRendererButtonClass(class) (G_TYPE_CHECK_CLASS_TYPE((class), cellRendererButton)) +#define getCellRendererButtonClass(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), cellRendererButtonType, cellRendererButtonClass)) + +typedef struct cellRendererButton cellRendererButton; +typedef struct cellRendererButtonClass cellRendererButtonClass; + +struct cellRendererButton { + GtkCellRenderer parent_instance; + char *text; +}; + +struct cellRendererButtonClass { + GtkCellRendererClass parent_class; +}; + +G_DEFINE_TYPE(cellRendererButton, cellRendererButton, GTK_TYPE_CELL_RENDERER) + +static void cellRendererButton_init(cellRendererButton *c) +{ + g_object_set(c, "mode", GTK_CELL_RENDERER_MODE_ACTIVATABLE, NULL); + // the standard cell renderers all do this + gtk_cell_renderer_set_padding(GTK_CELL_RENDERER(c), 2, 2); +} + +static void cellRendererButton_dispose(GObject *obj) +{ + G_OBJECT_CLASS(cellRendererButton_parent_class)->dispose(obj); +} + +static void cellRendererButton_finalize(GObject *obj) +{ + cellRendererButton *c = cellRendererButton(obj); + + if (c->text != NULL) { + g_free(c->text); + c->text = NULL; + } + G_OBJECT_CLASS(cellRendererButton_parent_class)->finalize(obj); +} + +static GtkSizeRequestMode cellRendererButton_get_request_mode(GtkCellRenderer *r) +{ + return GTK_SIZE_REQUEST_HEIGHT_FOR_WIDTH; +} + +// this is basically what GtkCellRendererToggle did in 3.10 and does in 3.20, as well as what the Foreign Drawing gtk3-demo demo does +// TODO how does this seem to work with highlight on 3.22, and does that work with 3.10 too +static GtkStyleContext *setButtonStyle(GtkWidget *widget) +{ + GtkStyleContext *base, *context; + GtkWidgetPath *path; + + base = gtk_widget_get_style_context(widget); + context = gtk_style_context_new(); + + path = gtk_widget_path_copy(gtk_style_context_get_path(base)); + gtk_widget_path_append_type(path, G_TYPE_NONE); + if (!uiprivFUTURE_gtk_widget_path_iter_set_object_name(path, -1, "button")) + // not on 3.20; try the type + gtk_widget_path_iter_set_object_type(path, -1, GTK_TYPE_BUTTON); + + gtk_style_context_set_path(context, path); + gtk_style_context_set_parent(context, base); + // the gtk3-demo example (which says we need to do this) uses gtk_widget_path_iter_get_state(path, -1) but that's not available until 3.14 + // TODO make a future for that too + gtk_style_context_set_state(context, gtk_style_context_get_state(base)); + gtk_widget_path_unref(path); + + // and if the above widget path screwery stil doesn't work, this will + gtk_style_context_add_class(context, GTK_STYLE_CLASS_BUTTON); + + return context; +} + +void unsetButtonStyle(GtkStyleContext *context) +{ + g_object_unref(context); +} + +// this is based on what GtkCellRendererText in GTK+ 3.22.30 does +// TODO compare to 3.10.9 (https://gitlab.gnome.org/GNOME/gtk/blob/3.10.9/gtk/gtkcellrenderertext.c) +static PangoLayout *cellRendererButtonPangoLayout(cellRendererButton *c, GtkWidget *widget) +{ + PangoLayout *layout; + + layout = gtk_widget_create_pango_layout(widget, c->text); + pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_NONE); + pango_layout_set_width(layout, -1); + pango_layout_set_wrap(layout, PANGO_WRAP_CHAR); + pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER); + return layout; +} + +// this is based on what GtkCellRendererText in GTK+ 3.22.30 does +// TODO compare to 3.10.9 (https://gitlab.gnome.org/GNOME/gtk/blob/3.10.9/gtk/gtkcellrenderertext.c) +static void cellRendererButtonSize(cellRendererButton *c, GtkWidget *widget, PangoLayout *layout, const GdkRectangle *cell_area, gint *xoff, gint *yoff, gint *width, gint *height) +{ + PangoRectangle rect; + gint xpad, ypad; + gfloat xalign, yalign; + + gtk_cell_renderer_get_padding(GTK_CELL_RENDERER(c), &xpad, &ypad); + pango_layout_get_pixel_extents(layout, NULL, &rect); + if (rect.width > cell_area->width - (2 * xpad)) + rect.width = cell_area->width - (2 * xpad); + if (rect.height > cell_area->height - (2 * ypad)) + rect.height = cell_area->height - (2 * ypad); + + gtk_cell_renderer_get_alignment(GTK_CELL_RENDERER(c), &xalign, &yalign); + if (gtk_widget_get_direction(widget) == GTK_TEXT_DIR_RTL) + xalign = 1.0 - xalign; + if (xoff != NULL) { + *xoff = cell_area->width - (rect.width + (2 * xpad)); + *xoff = (gint) ((gfloat) (*xoff) * xalign); + } + if (yoff != NULL) { + *yoff = cell_area->height - (rect.height + (2 * ypad)); + *yoff = (gint) ((gfloat) (*yoff) * yalign); + if (*yoff < 0) + *yoff = 0; + } + if (width != NULL) + *width = rect.width - (2 * xpad); + if (height != NULL) + *height = rect.height - (2 * ypad); +} + +// this is based on what GtkCellRendererText in GTK+ 3.22.30 does +// TODO compare to 3.10.9 (https://gitlab.gnome.org/GNOME/gtk/blob/3.10.9/gtk/gtkcellrenderertext.c) +static void cellRendererButton_get_preferred_width(GtkCellRenderer *r, GtkWidget *widget, gint *minimum, gint *natural) +{ + cellRendererButton *c = cellRendererButton(r); + gint xpad; + PangoLayout *layout; + PangoRectangle rect; + gint out; + + gtk_cell_renderer_get_padding(GTK_CELL_RENDERER(c), &xpad, NULL); + + layout = cellRendererButtonPangoLayout(c, widget); + pango_layout_get_extents(layout, NULL, &rect); + g_object_unref(layout); + + out = PANGO_PIXELS_CEIL(rect.width) + (2 * xpad); + if (rect.x > 0) + out += rect.x; + if (minimum != NULL) + *minimum = out; + if (natural != NULL) + *natural = out; +} + +// this is based on what GtkCellRendererText in GTK+ 3.22.30 does +// TODO compare to 3.10.9 (https://gitlab.gnome.org/GNOME/gtk/blob/3.10.9/gtk/gtkcellrenderertext.c) +static void cellRendererButton_get_preferred_height_for_width(GtkCellRenderer *r, GtkWidget *widget, gint width, gint *minimum, gint *natural) +{ + cellRendererButton *c = cellRendererButton(r); + gint xpad, ypad; + PangoLayout *layout; + gint height; + gint out; + + gtk_cell_renderer_get_padding(GTK_CELL_RENDERER(c), &xpad, &ypad); + + layout = cellRendererButtonPangoLayout(c, widget); + pango_layout_set_width(layout, (width + (xpad * 2)) * PANGO_SCALE); + pango_layout_get_pixel_size(layout, NULL, &height); + g_object_unref(layout); + + out = height + (ypad * 2); + if (minimum != NULL) + *minimum = out; + if (natural != NULL) + *natural = out; +} + +// this is based on what GtkCellRendererText in GTK+ 3.22.30 does +// TODO compare to 3.10.9 (https://gitlab.gnome.org/GNOME/gtk/blob/3.10.9/gtk/gtkcellrenderertext.c) +static void cellRendererButton_get_preferred_height(GtkCellRenderer *r, GtkWidget *widget, gint *minimum, gint *natural) +{ + gint width; + + gtk_cell_renderer_get_preferred_width(r, widget, &width, NULL); + gtk_cell_renderer_get_preferred_height_for_width(r, widget, width, minimum, natural); +} + +// this is based on what GtkCellRendererText in GTK+ 3.22.30 does +// TODO compare to 3.10.9 (https://gitlab.gnome.org/GNOME/gtk/blob/3.10.9/gtk/gtkcellrenderertext.c) +static void cellRendererButton_get_aligned_area(GtkCellRenderer *r, GtkWidget *widget, GtkCellRendererState flags, const GdkRectangle *cell_area, GdkRectangle *aligned_area) +{ + cellRendererButton *c = cellRendererButton(r); + PangoLayout *layout; + gint xoff, yoff; + gint width, height; + + layout = cellRendererButtonPangoLayout(c, widget); + cellRendererButtonSize(c, widget, layout, cell_area, + &xoff, &yoff, &width, &height); + + aligned_area->x = cell_area->x + xoff; + aligned_area->y = cell_area->y + yoff; + aligned_area->width = width; + aligned_area->height = height; + + g_object_unref(layout); +} + +// this is based on both what GtkCellRendererText on 3.22.30 does and what GtkCellRendererToggle does (TODO verify the latter; both on 3.10.9) +static void cellRendererButton_render(GtkCellRenderer *r, cairo_t *cr, GtkWidget *widget, const GdkRectangle *background_area, const GdkRectangle *cell_area, GtkCellRendererState flags) +{ + cellRendererButton *c = cellRendererButton(r); + gint xpad, ypad; + GdkRectangle alignedArea; + gint xoff, yoff; + GtkStyleContext *context; + PangoLayout *layout; + PangoRectangle rect; + + gtk_cell_renderer_get_padding(GTK_CELL_RENDERER(c), &xpad, &ypad); + layout = cellRendererButtonPangoLayout(c, widget); + cellRendererButtonSize(c, widget, layout, cell_area, + &xoff, &yoff, NULL, NULL); + + context = setButtonStyle(widget); + + gtk_render_background(context, cr, + background_area->x + xpad, + background_area->y + ypad, + background_area->width - (xpad * 2), + background_area->height - (ypad * 2)); + gtk_render_frame(context, cr, + background_area->x + xpad, + background_area->y + ypad, + background_area->width - (xpad * 2), + background_area->height - (ypad * 2)); + + pango_layout_get_pixel_extents(layout, NULL, &rect); + xoff -= rect.x; + gtk_render_layout(context, cr, + cell_area->x + xoff + xpad, + cell_area->y + yoff + ypad, + layout); + + unsetButtonStyle(context); + g_object_unref(layout); +} + +static guint clickedSignal; + +static gboolean cellRendererButton_activate(GtkCellRenderer *r, GdkEvent *e, GtkWidget *widget, const gchar *path, const GdkRectangle *background_area, const GdkRectangle *cell_area, GtkCellRendererState flags) +{ + g_signal_emit(r, clickedSignal, 0, path); + return TRUE; +} + +static GParamSpec *props[2] = { NULL, NULL }; + +static void cellRendererButton_set_property(GObject *object, guint prop, const GValue *value, GParamSpec *pspec) +{ + cellRendererButton *c = cellRendererButton(object); + + if (prop != 1) { + G_OBJECT_WARN_INVALID_PROPERTY_ID(c, prop, pspec); + return; + } + if (c->text != NULL) + g_free(c->text); + c->text = g_value_dup_string(value); + // GtkCellRendererText doesn't queue a redraw; we won't either +} + +static void cellRendererButton_get_property(GObject *object, guint prop, GValue *value, GParamSpec *pspec) +{ + cellRendererButton *c = cellRendererButton(object); + + if (prop != 1) { + G_OBJECT_WARN_INVALID_PROPERTY_ID(c, prop, pspec); + return; + } + g_value_set_string(value, c->text); +} + +static void cellRendererButton_class_init(cellRendererButtonClass *class) +{ + G_OBJECT_CLASS(class)->dispose = cellRendererButton_dispose; + G_OBJECT_CLASS(class)->finalize = cellRendererButton_finalize; + G_OBJECT_CLASS(class)->set_property = cellRendererButton_set_property; + G_OBJECT_CLASS(class)->get_property = cellRendererButton_get_property; + GTK_CELL_RENDERER_CLASS(class)->get_request_mode = cellRendererButton_get_request_mode; + GTK_CELL_RENDERER_CLASS(class)->get_preferred_width = cellRendererButton_get_preferred_width; + GTK_CELL_RENDERER_CLASS(class)->get_preferred_height_for_width = cellRendererButton_get_preferred_height_for_width; + GTK_CELL_RENDERER_CLASS(class)->get_preferred_height = cellRendererButton_get_preferred_height; + // don't provide a get_preferred_width_for_height() + GTK_CELL_RENDERER_CLASS(class)->get_aligned_area = cellRendererButton_get_aligned_area; + // don't provide a get_size() + GTK_CELL_RENDERER_CLASS(class)->render = cellRendererButton_render; + GTK_CELL_RENDERER_CLASS(class)->activate = cellRendererButton_activate; + // don't provide a start_editing() + + props[1] = g_param_spec_string("text", + "Text", + "Button text", + "", + G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS); + g_object_class_install_properties(G_OBJECT_CLASS(class), 2, props); + + clickedSignal = g_signal_new("clicked", + G_TYPE_FROM_CLASS(class), + G_SIGNAL_RUN_LAST, + 0, + NULL, NULL, NULL, + G_TYPE_NONE, + 1, G_TYPE_STRING); +} + +GtkCellRenderer *uiprivNewCellRendererButton(void) +{ + return GTK_CELL_RENDERER(g_object_new(cellRendererButtonType, NULL)); +} diff --git a/dep/libui/unix/checkbox.c b/dep/libui/unix/checkbox.c new file mode 100644 index 0000000..47f8514 --- /dev/null +++ b/dep/libui/unix/checkbox.c @@ -0,0 +1,78 @@ +// 10 june 2015 +#include "uipriv_unix.h" + +struct uiCheckbox { + uiUnixControl c; + GtkWidget *widget; + GtkButton *button; + GtkToggleButton *toggleButton; + GtkCheckButton *checkButton; + void (*onToggled)(uiCheckbox *, void *); + void *onToggledData; + gulong onToggledSignal; +}; + +uiUnixControlAllDefaults(uiCheckbox) + +static void onToggled(GtkToggleButton *b, gpointer data) +{ + uiCheckbox *c = uiCheckbox(data); + + (*(c->onToggled))(c, c->onToggledData); +} + +static void defaultOnToggled(uiCheckbox *c, void *data) +{ + // do nothing +} + +char *uiCheckboxText(uiCheckbox *c) +{ + return uiUnixStrdupText(gtk_button_get_label(c->button)); +} + +void uiCheckboxSetText(uiCheckbox *c, const char *text) +{ + gtk_button_set_label(GTK_BUTTON(c->button), text); +} + +void uiCheckboxOnToggled(uiCheckbox *c, void (*f)(uiCheckbox *, void *), void *data) +{ + c->onToggled = f; + c->onToggledData = data; +} + +int uiCheckboxChecked(uiCheckbox *c) +{ + return gtk_toggle_button_get_active(c->toggleButton) != FALSE; +} + +void uiCheckboxSetChecked(uiCheckbox *c, int checked) +{ + gboolean active; + + active = FALSE; + if (checked) + active = TRUE; + // we need to inhibit sending of ::toggled because this WILL send a ::toggled otherwise + g_signal_handler_block(c->toggleButton, c->onToggledSignal); + gtk_toggle_button_set_active(c->toggleButton, active); + g_signal_handler_unblock(c->toggleButton, c->onToggledSignal); +} + +uiCheckbox *uiNewCheckbox(const char *text) +{ + uiCheckbox *c; + + uiUnixNewControl(uiCheckbox, c); + + c->widget = gtk_check_button_new_with_label(text); + c->button = GTK_BUTTON(c->widget); + c->toggleButton = GTK_TOGGLE_BUTTON(c->widget); + c->checkButton = GTK_CHECK_BUTTON(c->widget); + + c->onToggledSignal = g_signal_connect(c->widget, "toggled", G_CALLBACK(onToggled), c); + uiCheckboxOnToggled(c, defaultOnToggled, NULL); + + return c; +} diff --git a/dep/libui/unix/child.c b/dep/libui/unix/child.c new file mode 100644 index 0000000..240cc82 --- /dev/null +++ b/dep/libui/unix/child.c @@ -0,0 +1,120 @@ +// 28 august 2015 +#include "uipriv_unix.h" + +// This file contains helpers for managing child controls. + +struct uiprivChild { + uiControl *c; + GtkWidget *widget; + + gboolean oldhexpand; + GtkAlign oldhalign; + gboolean oldvexpand; + GtkAlign oldvalign; + + // Some children can be boxed; that is, they can have an optionally-margined box around them. + // uiGroup, uiTab, and uiWindow all do this. + GtkWidget *box; + + // If the child is not boxed, this is its parent. + // If the child is boxed, this is the box. + GtkContainer *parent; + + // This flag is for users of these functions. + // For uiBox, this is "spaced". + // For uiTab, this is "margined". (uiGroup and uiWindow have to maintain their margined state themselves, since the margined state is independent of whether there is a child for those two.) + int flag; +}; + +uiprivChild *uiprivNewChild(uiControl *child, uiControl *parent, GtkContainer *parentContainer) +{ + uiprivChild *c; + + if (child == NULL) + return NULL; + + c = uiprivNew(uiprivChild); + c->c = child; + c->widget = GTK_WIDGET(uiControlHandle(c->c)); + + c->oldhexpand = gtk_widget_get_hexpand(c->widget); + c->oldhalign = gtk_widget_get_halign(c->widget); + c->oldvexpand = gtk_widget_get_vexpand(c->widget); + c->oldvalign = gtk_widget_get_valign(c->widget); + + uiControlSetParent(c->c, parent); + uiUnixControlSetContainer(uiUnixControl(c->c), parentContainer, FALSE); + c->parent = parentContainer; + + return c; +} + +uiprivChild *uiprivNewChildWithBox(uiControl *child, uiControl *parent, GtkContainer *parentContainer, int margined) +{ + uiprivChild *c; + GtkWidget *box; + + if (child == NULL) + return NULL; + box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + gtk_widget_show(box); + c = uiprivNewChild(child, parent, GTK_CONTAINER(box)); + gtk_widget_set_hexpand(c->widget, TRUE); + gtk_widget_set_halign(c->widget, GTK_ALIGN_FILL); + gtk_widget_set_vexpand(c->widget, TRUE); + gtk_widget_set_valign(c->widget, GTK_ALIGN_FILL); + c->box = box; + gtk_container_add(parentContainer, c->box); + uiprivChildSetMargined(c, margined); + return c; +} + +void uiprivChildRemove(uiprivChild *c) +{ + uiControlSetParent(c->c, NULL); + uiUnixControlSetContainer(uiUnixControl(c->c), c->parent, TRUE); + + gtk_widget_set_hexpand(c->widget, c->oldhexpand); + gtk_widget_set_halign(c->widget, c->oldhalign); + gtk_widget_set_vexpand(c->widget, c->oldvexpand); + gtk_widget_set_valign(c->widget, c->oldvalign); + + if (c->box != NULL) + gtk_widget_destroy(c->box); + + uiprivFree(c); +} + +void uiprivChildDestroy(uiprivChild *c) +{ + uiControl *child; + + child = c->c; + uiprivChildRemove(c); + uiControlDestroy(child); +} + +GtkWidget *uiprivChildWidget(uiprivChild *c) +{ + return c->widget; +} + +int uiprivChildFlag(uiprivChild *c) +{ + return c->flag; +} + +void uiprivChildSetFlag(uiprivChild *c, int flag) +{ + c->flag = flag; +} + +GtkWidget *uiprivChildBox(uiprivChild *c) +{ + return c->box; +} + +void uiprivChildSetMargined(uiprivChild *c, int margined) +{ + uiprivSetMargined(GTK_CONTAINER(c->box), margined); +} diff --git a/dep/libui/unix/colorbutton.c b/dep/libui/unix/colorbutton.c new file mode 100644 index 0000000..393b16f --- /dev/null +++ b/dep/libui/unix/colorbutton.c @@ -0,0 +1,80 @@ +// 15 may 2016 +#include "uipriv_unix.h" + +struct uiColorButton { + uiUnixControl c; + GtkWidget *widget; + GtkButton *button; + GtkColorButton *cb; + GtkColorChooser *cc; + void (*onChanged)(uiColorButton *, void *); + void *onChangedData; +}; + +uiUnixControlAllDefaults(uiColorButton) + +static void onColorSet(GtkColorButton *button, gpointer data) +{ + uiColorButton *b = uiColorButton(data); + + (*(b->onChanged))(b, b->onChangedData); +} + +static void defaultOnChanged(uiColorButton *b, void *data) +{ + // do nothing +} + +void uiColorButtonColor(uiColorButton *b, double *r, double *g, double *bl, double *a) +{ + GdkRGBA rgba; + + gtk_color_chooser_get_rgba(b->cc, &rgba); + *r = rgba.red; + *g = rgba.green; + *bl = rgba.blue; + *a = rgba.alpha; +} + +void uiColorButtonSetColor(uiColorButton *b, double r, double g, double bl, double a) +{ + GdkRGBA rgba; + + rgba.red = r; + rgba.green = g; + rgba.blue = bl; + rgba.alpha = a; + // no need to inhibit the signal; color-set is documented as only being sent when the user changes the color + gtk_color_chooser_set_rgba(b->cc, &rgba); +} + +void uiColorButtonOnChanged(uiColorButton *b, void (*f)(uiColorButton *, void *), void *data) +{ + b->onChanged = f; + b->onChangedData = data; +} + +uiColorButton *uiNewColorButton(void) +{ + uiColorButton *b; + GdkRGBA black; + + uiUnixNewControl(uiColorButton, b); + + // I'm not sure what the initial color is; set up a real one + black.red = 0.0; + black.green = 0.0; + black.blue = 0.0; + black.alpha = 1.0; + b->widget = gtk_color_button_new_with_rgba(&black); + b->button = GTK_BUTTON(b->widget); + b->cb = GTK_COLOR_BUTTON(b->widget); + b->cc = GTK_COLOR_CHOOSER(b->widget); + + gtk_color_chooser_set_use_alpha(b->cc, TRUE); + + g_signal_connect(b->widget, "color-set", G_CALLBACK(onColorSet), b); + uiColorButtonOnChanged(b, defaultOnChanged, NULL); + + return b; +} diff --git a/dep/libui/unix/combobox.c b/dep/libui/unix/combobox.c new file mode 100644 index 0000000..6fed804 --- /dev/null +++ b/dep/libui/unix/combobox.c @@ -0,0 +1,66 @@ +// 11 june 2015 +#include "uipriv_unix.h" + +struct uiCombobox { + uiUnixControl c; + GtkWidget *widget; + GtkComboBox *combobox; + GtkComboBoxText *comboboxText; + void (*onSelected)(uiCombobox *, void *); + void *onSelectedData; + gulong onSelectedSignal; +}; + +uiUnixControlAllDefaults(uiCombobox) + +static void onChanged(GtkComboBox *cbox, gpointer data) +{ + uiCombobox *c = uiCombobox(data); + + (*(c->onSelected))(c, c->onSelectedData); +} + +static void defaultOnSelected(uiCombobox *c, void *data) +{ + // do nothing +} + +void uiComboboxAppend(uiCombobox *c, const char *text) +{ + gtk_combo_box_text_append(c->comboboxText, NULL, text); +} + +int uiComboboxSelected(uiCombobox *c) +{ + return gtk_combo_box_get_active(c->combobox); +} + +void uiComboboxSetSelected(uiCombobox *c, int n) +{ + // we need to inhibit sending of ::changed because this WILL send a ::changed otherwise + g_signal_handler_block(c->combobox, c->onSelectedSignal); + gtk_combo_box_set_active(c->combobox, n); + g_signal_handler_unblock(c->combobox, c->onSelectedSignal); +} + +void uiComboboxOnSelected(uiCombobox *c, void (*f)(uiCombobox *c, void *data), void *data) +{ + c->onSelected = f; + c->onSelectedData = data; +} + +uiCombobox *uiNewCombobox(void) +{ + uiCombobox *c; + + uiUnixNewControl(uiCombobox, c); + + c->widget = gtk_combo_box_text_new(); + c->combobox = GTK_COMBO_BOX(c->widget); + c->comboboxText = GTK_COMBO_BOX_TEXT(c->widget); + + c->onSelectedSignal = g_signal_connect(c->widget, "changed", G_CALLBACK(onChanged), c); + uiComboboxOnSelected(c, defaultOnSelected, NULL); + + return c; +} diff --git a/dep/libui/unix/control.c b/dep/libui/unix/control.c new file mode 100644 index 0000000..f6fdcea --- /dev/null +++ b/dep/libui/unix/control.c @@ -0,0 +1,14 @@ +// 16 august 2015 +#include "uipriv_unix.h" + +void uiUnixControlSetContainer(uiUnixControl *c, GtkContainer *container, gboolean remove) +{ + (*(c->SetContainer))(c, container, remove); +} + +#define uiUnixControlSignature 0x556E6978 + +uiUnixControl *uiUnixAllocControl(size_t n, uint32_t typesig, const char *typenamestr) +{ + return uiUnixControl(uiAllocControl(n, uiUnixControlSignature, typesig, typenamestr)); +} diff --git a/dep/libui/unix/datetimepicker.c b/dep/libui/unix/datetimepicker.c new file mode 100644 index 0000000..8ca3a27 --- /dev/null +++ b/dep/libui/unix/datetimepicker.c @@ -0,0 +1,675 @@ +// 4 september 2015 +#include "uipriv_unix.h" + +// LONGTERM imitate gnome-calendar's day/month/year entries above the calendar +// LONGTERM allow entering a 24-hour hour in the hour spinbutton and adjust accordingly + +#define uiprivDateTimePickerWidgetType (uiprivDateTimePickerWidget_get_type()) +#define uiprivDateTimePickerWidget(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), uiprivDateTimePickerWidgetType, uiprivDateTimePickerWidget)) +#define isDateTimePickerWidget(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), uiprivDateTimePickerWidgetType)) +#define uiprivDateTimePickerWidgetClass(class) (G_TYPE_CHECK_CLASS_CAST((class), uiprivDateTimePickerWidgetType, uiprivDateTimePickerWidgetClass)) +#define isDateTimePickerWidgetClass(class) (G_TYPE_CHECK_CLASS_TYPE((class), uiprivDateTimePickerWidget)) +#define getDateTimePickerWidgetClass(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), uiprivDateTimePickerWidgetType, uiprivDateTimePickerWidgetClass)) + +typedef struct uiprivDateTimePickerWidget uiprivDateTimePickerWidget; +typedef struct uiprivDateTimePickerWidgetClass uiprivDateTimePickerWidgetClass; + +struct uiprivDateTimePickerWidget { + GtkToggleButton parent_instance; + + gulong toggledSignal; + + gboolean hasTime; + gboolean hasDate; + + GtkWidget *window; + GtkWidget *box; + GtkWidget *calendar; + GtkWidget *timebox; + GtkWidget *hours; + GtkWidget *minutes; + GtkWidget *seconds; + GtkWidget *ampm; + + gulong calendarBlock; + gulong hoursBlock; + gulong minutesBlock; + gulong secondsBlock; + gulong ampmBlock; + + GdkDevice *keyboard; + GdkDevice *mouse; +}; + +struct uiprivDateTimePickerWidgetClass { + GtkToggleButtonClass parent_class; +}; + +G_DEFINE_TYPE(uiprivDateTimePickerWidget, uiprivDateTimePickerWidget, GTK_TYPE_TOGGLE_BUTTON) + +static int realSpinValue(GtkSpinButton *spinButton) +{ + GtkAdjustment *adj; + + adj = gtk_spin_button_get_adjustment(spinButton); + return (int) gtk_adjustment_get_value(adj); +} + +static void setRealSpinValue(GtkSpinButton *spinButton, int value, gulong block) +{ + GtkAdjustment *adj; + + g_signal_handler_block(spinButton, block); + adj = gtk_spin_button_get_adjustment(spinButton); + gtk_adjustment_set_value(adj, value); + g_signal_handler_unblock(spinButton, block); +} + +static GDateTime *selected(uiprivDateTimePickerWidget *d) +{ + // choose a day for which all times are likely to be valid for the default date in case we're only dealing with time + guint year = 1970, month = 1, day = 1; + guint hour = 0, minute = 0, second = 0; + + if (d->hasDate) { + gtk_calendar_get_date(GTK_CALENDAR(d->calendar), &year, &month, &day); + month++; // GtkCalendar/GDateTime differences + } + if (d->hasTime) { + hour = realSpinValue(GTK_SPIN_BUTTON(d->hours)); + if (realSpinValue(GTK_SPIN_BUTTON(d->ampm)) != 0) + hour += 12; + minute = realSpinValue(GTK_SPIN_BUTTON(d->minutes)); + second = realSpinValue(GTK_SPIN_BUTTON(d->seconds)); + } + return g_date_time_new_local(year, month, day, hour, minute, second); +} + +static void setLabel(uiprivDateTimePickerWidget *d) +{ + GDateTime *dt; + char *fmt; + char *msg; + gboolean free; + + dt = selected(d); + free = FALSE; + if (d->hasDate && d->hasTime) { + // don't use D_T_FMT; that's too verbose + fmt = g_strdup_printf("%s %s", nl_langinfo(D_FMT), nl_langinfo(T_FMT)); + free = TRUE; + } else if (d->hasDate) + fmt = nl_langinfo(D_FMT); + else + fmt = nl_langinfo(T_FMT); + msg = g_date_time_format(dt, fmt); + gtk_button_set_label(GTK_BUTTON(d), msg); + g_free(msg); + if (free) + g_free(fmt); + g_date_time_unref(dt); +} + +static int changedSignal; + +static void dateTimeChanged(uiprivDateTimePickerWidget *d) +{ + g_signal_emit(d, changedSignal, 0); + setLabel(d); + // TODO fire event here instead? +} + +// we don't want ::toggled to be sent again +static void setActive(uiprivDateTimePickerWidget *d, gboolean active) +{ + g_signal_handler_block(d, d->toggledSignal); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(d), active); + g_signal_handler_unblock(d, d->toggledSignal); +} + +// like startGrab() below, a lot of this is in the order that GtkComboBox does it +static void endGrab(uiprivDateTimePickerWidget *d) +{ + if (d->keyboard != NULL) + gdk_device_ungrab(d->keyboard, GDK_CURRENT_TIME); + gdk_device_ungrab(d->mouse, GDK_CURRENT_TIME); + gtk_device_grab_remove(d->window, d->mouse); + d->keyboard = NULL; + d->mouse = NULL; +} + +static void hidePopup(uiprivDateTimePickerWidget *d) +{ + endGrab(d); + gtk_widget_hide(d->window); + setActive(d, FALSE); +} + +// this consolidates a good chunk of what GtkComboBox does +static gboolean startGrab(uiprivDateTimePickerWidget *d) +{ + GdkDevice *dev; + guint32 time; + GdkWindow *window; + GdkDevice *keyboard, *mouse; + + dev = gtk_get_current_event_device(); + if (dev == NULL) { + // this is what GtkComboBox does + // since no device was set, just use the first available "master device" + GdkDisplay *disp; + GdkDeviceManager *dm; + GList *list; + + disp = gtk_widget_get_display(GTK_WIDGET(d)); + dm = gdk_display_get_device_manager(disp); + list = gdk_device_manager_list_devices(dm, GDK_DEVICE_TYPE_MASTER); + dev = (GdkDevice *) (list->data); + g_list_free(list); + } + + time = gtk_get_current_event_time(); + keyboard = dev; + mouse = gdk_device_get_associated_device(dev); + if (gdk_device_get_source(dev) != GDK_SOURCE_KEYBOARD) { + dev = mouse; + mouse = keyboard; + keyboard = dev; + } + + window = gtk_widget_get_window(d->window); + if (keyboard != NULL) + if (gdk_device_grab(keyboard, window, + GDK_OWNERSHIP_WINDOW, TRUE, + GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK, + NULL, time) != GDK_GRAB_SUCCESS) + return FALSE; + if (mouse != NULL) + if (gdk_device_grab(mouse, window, + GDK_OWNERSHIP_WINDOW, TRUE, + GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK, + NULL, time) != GDK_GRAB_SUCCESS) { + if (keyboard != NULL) + gdk_device_ungrab(keyboard, time); + return FALSE; + } + + gtk_device_grab_add(d->window, mouse, TRUE); + d->keyboard = keyboard; + d->mouse = mouse; + return TRUE; +} + +// based on gtk_combo_box_list_position() in the GTK+ source code +static void allocationToScreen(uiprivDateTimePickerWidget *d, gint *x, gint *y) +{ + GdkWindow *window; + GtkAllocation a; + GtkRequisition aWin; + GdkScreen *screen; + GdkRectangle workarea; + int otherY; + + gtk_widget_get_allocation(GTK_WIDGET(d), &a); + gtk_widget_get_preferred_size(d->window, &aWin, NULL); + *x = 0; + *y = 0; + if (!gtk_widget_get_has_window(GTK_WIDGET(d))) { + *x = a.x; + *y = a.y; + } + window = gtk_widget_get_window(GTK_WIDGET(d)); + gdk_window_get_root_coords(window, *x, *y, x, y); + if (gtk_widget_get_direction(GTK_WIDGET(d)) == GTK_TEXT_DIR_RTL) + *x += a.width - aWin.width; + + // now adjust to prevent the box from going offscreen + screen = gtk_widget_get_screen(GTK_WIDGET(d)); + gdk_screen_get_monitor_workarea(screen, + gdk_screen_get_monitor_at_window(screen, window), + &workarea); + if (*x < workarea.x) // too far to the left? + *x = workarea.x; + else if (*x + aWin.width > (workarea.x + workarea.width)) // too far to the right? + *x = (workarea.x + workarea.width) - aWin.width; + // this isn't the same algorithm used by GtkComboBox + // first, get our two choices; *y for down and otherY for up + otherY = *y - aWin.height; + *y += a.height; + // and use otherY if we're too low + if (*y + aWin.height >= workarea.y + workarea.height) + *y = otherY; +} + +static void showPopup(uiprivDateTimePickerWidget *d) +{ + GtkWidget *toplevel; + gint x, y; + + // GtkComboBox does it + toplevel = gtk_widget_get_toplevel(GTK_WIDGET(d)); + if (GTK_IS_WINDOW(toplevel)) + gtk_window_group_add_window(gtk_window_get_group(GTK_WINDOW(toplevel)), GTK_WINDOW(d->window)); + + allocationToScreen(d, &x, &y); + gtk_window_move(GTK_WINDOW(d->window), x, y); + + gtk_widget_show(d->window); + setActive(d, TRUE); + + if (!startGrab(d)) + hidePopup(d); +} + +static void onToggled(GtkToggleButton *b, gpointer data) +{ + uiprivDateTimePickerWidget *d = uiprivDateTimePickerWidget(b); + + if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(d))) + showPopup(d); + else + hidePopup(d); +} + +static gboolean grabBroken(GtkWidget *w, GdkEventGrabBroken *e, gpointer data) +{ + uiprivDateTimePickerWidget *d = uiprivDateTimePickerWidget(data); + + hidePopup(d); + return TRUE; // this is what GtkComboBox does +} + +static gboolean buttonReleased(GtkWidget *w, GdkEventButton *e, gpointer data) +{ + uiprivDateTimePickerWidget *d = uiprivDateTimePickerWidget(data); + int winx, winy; + GtkAllocation wina; + gboolean in; + + gtk_widget_get_allocation(d->window, &wina); + winx = 0; + winy = 0; + if (!gtk_widget_get_has_window(d->window)) { + winx = wina.x; + winy = wina.y; + } + gdk_window_get_root_coords(gtk_widget_get_window(d->window), winx, winy, &winx, &winy); + in = TRUE; + if (e->x_root < winx) + in = FALSE; + if (e->x_root >= (winx + wina.width)) + in = FALSE; + if (e->y_root < winy) + in = FALSE; + if (e->y_root >= (winy + wina.height)) + in = FALSE; + if (!in) + hidePopup(d); + return TRUE; // this is what GtkComboBox does +} + +static gint hoursSpinboxInput(GtkSpinButton *sb, gpointer ptr, gpointer data) +{ + double *out = (double *) ptr; + const gchar *text; + int value; + + text = gtk_entry_get_text(GTK_ENTRY(sb)); + value = (int) g_strtod(text, NULL); + if (value < 0 || value > 12) + return GTK_INPUT_ERROR; + if (value == 12) // 12 to the user is 0 internally + value = 0; + *out = (double) value; + return TRUE; +} + +static gboolean hoursSpinboxOutput(GtkSpinButton *sb, gpointer data) +{ + gchar *text; + int value; + + value = realSpinValue(sb); + if (value == 0) // 0 internally is 12 to the user + value = 12; + text = g_strdup_printf("%d", value); + gtk_entry_set_text(GTK_ENTRY(sb), text); + g_free(text); + return TRUE; +} + +static gboolean zeroPadSpinbox(GtkSpinButton *sb, gpointer data) +{ + gchar *text; + int value; + + value = realSpinValue(sb); + text = g_strdup_printf("%02d", value); + gtk_entry_set_text(GTK_ENTRY(sb), text); + g_free(text); + return TRUE; +} + +// this is really hacky but we can't use GtkCombobox here :( +static gint ampmSpinboxInput(GtkSpinButton *sb, gpointer ptr, gpointer data) +{ + double *out = (double *) ptr; + const gchar *text; + char firstAM, firstPM; + + text = gtk_entry_get_text(GTK_ENTRY(sb)); + // LONGTERM don't use ASCII here for case insensitivity + firstAM = g_ascii_tolower(nl_langinfo(AM_STR)[0]); + firstPM = g_ascii_tolower(nl_langinfo(PM_STR)[0]); + for (; *text != '\0'; text++) + if (g_ascii_tolower(*text) == firstAM) { + *out = 0; + return TRUE; + } else if (g_ascii_tolower(*text) == firstPM) { + *out = 1; + return TRUE; + } + return GTK_INPUT_ERROR; +} + +static gboolean ampmSpinboxOutput(GtkSpinButton *sb, gpointer data) +{ + int value; + + value = gtk_spin_button_get_value_as_int(sb); + if (value == 0) + gtk_entry_set_text(GTK_ENTRY(sb), nl_langinfo(AM_STR)); + else + gtk_entry_set_text(GTK_ENTRY(sb), nl_langinfo(PM_STR)); + return TRUE; +} + +static void spinboxChanged(GtkSpinButton *sb, gpointer data) +{ + uiprivDateTimePickerWidget *d = uiprivDateTimePickerWidget(data); + + dateTimeChanged(d); +} + +static GtkWidget *newSpinbox(uiprivDateTimePickerWidget *d, int min, int max, gint (*input)(GtkSpinButton *, gpointer, gpointer), gboolean (*output)(GtkSpinButton *, gpointer), gulong *block) +{ + GtkWidget *sb; + + sb = gtk_spin_button_new_with_range(min, max, 1); + gtk_spin_button_set_digits(GTK_SPIN_BUTTON(sb), 0); + gtk_spin_button_set_wrap(GTK_SPIN_BUTTON(sb), TRUE); + gtk_orientable_set_orientation(GTK_ORIENTABLE(sb), GTK_ORIENTATION_VERTICAL); + *block = g_signal_connect(sb, "value-changed", G_CALLBACK(spinboxChanged), d); + if (input != NULL) + g_signal_connect(sb, "input", G_CALLBACK(input), NULL); + if (output != NULL) + g_signal_connect(sb, "output", G_CALLBACK(output), NULL); + return sb; +} + +static void dateChanged(GtkCalendar *c, gpointer data) +{ + uiprivDateTimePickerWidget *d = uiprivDateTimePickerWidget(data); + + dateTimeChanged(d); +} + +static void setDateOnly(uiprivDateTimePickerWidget *d) +{ + d->hasTime = FALSE; + gtk_container_remove(GTK_CONTAINER(d->box), d->timebox); +} + +static void setTimeOnly(uiprivDateTimePickerWidget *d) +{ + d->hasDate = FALSE; + gtk_container_remove(GTK_CONTAINER(d->box), d->calendar); +} + +static void uiprivDateTimePickerWidget_setTime(uiprivDateTimePickerWidget *d, GDateTime *dt) +{ + gint year, month, day; + gint hour; + + // notice how we block signals from firing + if (d->hasDate) { + g_date_time_get_ymd(dt, &year, &month, &day); + month--; // GDateTime/GtkCalendar differences + g_signal_handler_block(d->calendar, d->calendarBlock); + gtk_calendar_select_month(GTK_CALENDAR(d->calendar), month, year); + gtk_calendar_select_day(GTK_CALENDAR(d->calendar), day); + g_signal_handler_unblock(d->calendar, d->calendarBlock); + } + if (d->hasTime) { + hour = g_date_time_get_hour(dt); + if (hour >= 12) { + hour -= 12; + setRealSpinValue(GTK_SPIN_BUTTON(d->ampm), 1, d->ampmBlock); + } + setRealSpinValue(GTK_SPIN_BUTTON(d->hours), hour, d->hoursBlock); + setRealSpinValue(GTK_SPIN_BUTTON(d->minutes), g_date_time_get_minute(dt), d->minutesBlock); + setRealSpinValue(GTK_SPIN_BUTTON(d->seconds), g_date_time_get_seconds(dt), d->secondsBlock); + } + g_date_time_unref(dt); +} + +static void uiprivDateTimePickerWidget_init(uiprivDateTimePickerWidget *d) +{ + d->window = gtk_window_new(GTK_WINDOW_POPUP); + gtk_window_set_resizable(GTK_WINDOW(d->window), FALSE); + gtk_window_set_attached_to(GTK_WINDOW(d->window), GTK_WIDGET(d)); + gtk_window_set_decorated(GTK_WINDOW(d->window), FALSE); + gtk_window_set_deletable(GTK_WINDOW(d->window), FALSE); + gtk_window_set_type_hint(GTK_WINDOW(d->window), GDK_WINDOW_TYPE_HINT_COMBO); + gtk_window_set_skip_taskbar_hint(GTK_WINDOW(d->window), TRUE); + gtk_window_set_skip_pager_hint(GTK_WINDOW(d->window), TRUE); + gtk_window_set_has_resize_grip(GTK_WINDOW(d->window), FALSE); + gtk_container_set_border_width(GTK_CONTAINER(d->window), 12); + // and make it stand out a bit + gtk_style_context_add_class(gtk_widget_get_style_context(d->window), "frame"); + + d->box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6); + gtk_container_add(GTK_CONTAINER(d->window), d->box); + + d->calendar = gtk_calendar_new(); + d->calendarBlock = g_signal_connect(d->calendar, "day-selected", G_CALLBACK(dateChanged), d); + gtk_container_add(GTK_CONTAINER(d->box), d->calendar); + + d->timebox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6); + gtk_widget_set_valign(d->timebox, GTK_ALIGN_CENTER); + gtk_container_add(GTK_CONTAINER(d->box), d->timebox); + + d->hours = newSpinbox(d, 0, 11, hoursSpinboxInput, hoursSpinboxOutput, &(d->hoursBlock)); + gtk_container_add(GTK_CONTAINER(d->timebox), d->hours); + + gtk_container_add(GTK_CONTAINER(d->timebox), + gtk_label_new(":")); + + d->minutes = newSpinbox(d, 0, 59, NULL, zeroPadSpinbox, &(d->minutesBlock)); + gtk_container_add(GTK_CONTAINER(d->timebox), d->minutes); + + gtk_container_add(GTK_CONTAINER(d->timebox), + gtk_label_new(":")); + + d->seconds = newSpinbox(d, 0, 59, NULL, zeroPadSpinbox, &(d->secondsBlock)); + gtk_container_add(GTK_CONTAINER(d->timebox), d->seconds); + + // LONGTERM this should be the case, but that interferes with grabs + // switch to it when we can drop GTK+ 3.10 and use popovers +#if 0 + d->ampm = gtk_combo_box_text_new(); + gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(d->ampm), NULL, "AM"); + gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(d->ampm), NULL, "PM"); +#endif + d->ampm = newSpinbox(d, 0, 1, ampmSpinboxInput, ampmSpinboxOutput, &(d->ampmBlock)); + gtk_spin_button_set_numeric(GTK_SPIN_BUTTON(d->ampm), FALSE); + gtk_widget_set_valign(d->ampm, GTK_ALIGN_CENTER); + gtk_container_add(GTK_CONTAINER(d->timebox), d->ampm); + + gtk_widget_show_all(d->box); + + g_signal_connect(d->window, "grab-broken-event", G_CALLBACK(grabBroken), d); + g_signal_connect(d->window, "button-release-event", G_CALLBACK(buttonReleased), d); + + d->toggledSignal = g_signal_connect(d, "toggled", G_CALLBACK(onToggled), NULL); + d->keyboard = NULL; + d->mouse = NULL; + + d->hasTime = TRUE; + d->hasDate = TRUE; + + // set the current date/time + uiprivDateTimePickerWidget_setTime(d, g_date_time_new_now_local()); +} + +static void uiprivDateTimePickerWidget_dispose(GObject *obj) +{ + uiprivDateTimePickerWidget *d = uiprivDateTimePickerWidget(obj); + + if (d->window != NULL) { + gtk_widget_destroy(d->window); + d->window = NULL; + } + G_OBJECT_CLASS(uiprivDateTimePickerWidget_parent_class)->dispose(obj); +} + +static void uiprivDateTimePickerWidget_finalize(GObject *obj) +{ + G_OBJECT_CLASS(uiprivDateTimePickerWidget_parent_class)->finalize(obj); +} + +static void uiprivDateTimePickerWidget_class_init(uiprivDateTimePickerWidgetClass *class) +{ + G_OBJECT_CLASS(class)->dispose = uiprivDateTimePickerWidget_dispose; + G_OBJECT_CLASS(class)->finalize = uiprivDateTimePickerWidget_finalize; + + changedSignal = g_signal_new("changed", + G_TYPE_FROM_CLASS(class), + G_SIGNAL_RUN_LAST, + 0, + NULL, NULL, NULL, + G_TYPE_NONE, + 0); +} + +struct uiDateTimePicker { + uiUnixControl c; + GtkWidget *widget; + uiprivDateTimePickerWidget *d; + void (*onChanged)(uiDateTimePicker *, void *); + void *onChangedData; + gulong setBlock; +}; + +uiUnixControlAllDefaults(uiDateTimePicker) + +static void defaultOnChanged(uiDateTimePicker *d, void *data) +{ + // do nothing +} + +void uiDateTimePickerTime(uiDateTimePicker *d, struct tm *time) +{ + time_t t; + struct tm tmbuf; + GDateTime *dt; + + dt = selected(d->d); + t = g_date_time_to_unix(dt); + g_date_time_unref(dt); + + // Copy time to minimize a race condition + // time.h functions use global non-thread-safe data + tmbuf = *localtime(&t); + memcpy(time, &tmbuf, sizeof (struct tm)); +} + +void uiDateTimePickerSetTime(uiDateTimePicker *d, const struct tm *time) +{ + time_t t; + struct tm tmbuf; + + // TODO find a better way to avoid this; possibly by removing the signal entirely, or the call to dateTimeChanged() (most likely both) + g_signal_handler_block(d->d, d->setBlock); + + // Copy time because mktime() modifies its argument + memcpy(&tmbuf, time, sizeof (struct tm)); + t = mktime(&tmbuf); + + uiprivDateTimePickerWidget_setTime(d->d, g_date_time_new_from_unix_local(t)); + dateTimeChanged(d->d); + + g_signal_handler_unblock(d->d, d->setBlock); +} + +void uiDateTimePickerOnChanged(uiDateTimePicker *d, void (*f)(uiDateTimePicker *, void *), void *data) +{ + d->onChanged = f; + d->onChangedData = data; +} + +static void onChanged(uiprivDateTimePickerWidget *d, gpointer data) +{ + uiDateTimePicker *c; + + c = uiDateTimePicker(data); + (*(c->onChanged))(c, c->onChangedData); +} + +static GtkWidget *newDTP(void) +{ + GtkWidget *w; + + w = GTK_WIDGET(g_object_new(uiprivDateTimePickerWidgetType, "label", "", NULL)); + setLabel(uiprivDateTimePickerWidget(w)); + return w; +} + +static GtkWidget *newDP(void) +{ + GtkWidget *w; + + w = GTK_WIDGET(g_object_new(uiprivDateTimePickerWidgetType, "label", "", NULL)); + setDateOnly(uiprivDateTimePickerWidget(w)); + setLabel(uiprivDateTimePickerWidget(w)); + return w; +} + +static GtkWidget *newTP(void) +{ + GtkWidget *w; + + w = GTK_WIDGET(g_object_new(uiprivDateTimePickerWidgetType, "label", "", NULL)); + setTimeOnly(uiprivDateTimePickerWidget(w)); + setLabel(uiprivDateTimePickerWidget(w)); + return w; +} + +uiDateTimePicker *finishNewDateTimePicker(GtkWidget *(*fn)(void)) +{ + uiDateTimePicker *d; + + uiUnixNewControl(uiDateTimePicker, d); + + d->widget = (*fn)(); + d->d = uiprivDateTimePickerWidget(d->widget); + d->setBlock = g_signal_connect(d->widget, "changed", G_CALLBACK(onChanged), d); + uiDateTimePickerOnChanged(d, defaultOnChanged, NULL); + + return d; +} + +uiDateTimePicker *uiNewDateTimePicker(void) +{ + return finishNewDateTimePicker(newDTP); +} + +uiDateTimePicker *uiNewDatePicker(void) +{ + return finishNewDateTimePicker(newDP); +} + +uiDateTimePicker *uiNewTimePicker(void) +{ + return finishNewDateTimePicker(newTP); +} diff --git a/dep/libui/unix/debug.c b/dep/libui/unix/debug.c new file mode 100644 index 0000000..fd97c9e --- /dev/null +++ b/dep/libui/unix/debug.c @@ -0,0 +1,14 @@ +// 13 may 2016 +#include "uipriv_unix.h" + +// LONGTERM don't halt on release builds + +void uiprivRealBug(const char *file, const char *line, const char *func, const char *prefix, const char *format, va_list ap) +{ + char *a, *b; + + a = g_strdup_printf("[libui] %s:%s:%s() %s", file, line, func, prefix); + b = g_strdup_vprintf(format, ap); + g_critical("%s%s", a, b); + G_BREAKPOINT(); +} diff --git a/dep/libui/unix/draw.c b/dep/libui/unix/draw.c new file mode 100644 index 0000000..a8f26d7 --- /dev/null +++ b/dep/libui/unix/draw.c @@ -0,0 +1,143 @@ +// 6 september 2015 +#include "uipriv_unix.h" +#include "draw.h" + +uiDrawContext *uiprivNewContext(cairo_t *cr, GtkStyleContext *style) +{ + uiDrawContext *c; + + c = uiprivNew(uiDrawContext); + c->cr = cr; + c->style = style; + return c; +} + +void uiprivFreeContext(uiDrawContext *c) +{ + // free neither cr nor style; we own neither + uiprivFree(c); +} + +static cairo_pattern_t *mkbrush(uiDrawBrush *b) +{ + cairo_pattern_t *pat; + size_t i; + + switch (b->Type) { + case uiDrawBrushTypeSolid: + pat = cairo_pattern_create_rgba(b->R, b->G, b->B, b->A); + break; + case uiDrawBrushTypeLinearGradient: + pat = cairo_pattern_create_linear(b->X0, b->Y0, b->X1, b->Y1); + break; + case uiDrawBrushTypeRadialGradient: + // make the start circle radius 0 to make it a point + pat = cairo_pattern_create_radial( + b->X0, b->Y0, 0, + b->X1, b->Y1, b->OuterRadius); + break; +// case uiDrawBrushTypeImage: + } + if (cairo_pattern_status(pat) != CAIRO_STATUS_SUCCESS) + uiprivImplBug("error creating pattern in mkbrush(): %s", + cairo_status_to_string(cairo_pattern_status(pat))); + switch (b->Type) { + case uiDrawBrushTypeLinearGradient: + case uiDrawBrushTypeRadialGradient: + for (i = 0; i < b->NumStops; i++) + cairo_pattern_add_color_stop_rgba(pat, + b->Stops[i].Pos, + b->Stops[i].R, + b->Stops[i].G, + b->Stops[i].B, + b->Stops[i].A); + } + return pat; +} + +void uiDrawStroke(uiDrawContext *c, uiDrawPath *path, uiDrawBrush *b, uiDrawStrokeParams *p) +{ + cairo_pattern_t *pat; + + uiprivRunPath(path, c->cr); + pat = mkbrush(b); + cairo_set_source(c->cr, pat); + switch (p->Cap) { + case uiDrawLineCapFlat: + cairo_set_line_cap(c->cr, CAIRO_LINE_CAP_BUTT); + break; + case uiDrawLineCapRound: + cairo_set_line_cap(c->cr, CAIRO_LINE_CAP_ROUND); + break; + case uiDrawLineCapSquare: + cairo_set_line_cap(c->cr, CAIRO_LINE_CAP_SQUARE); + break; + } + switch (p->Join) { + case uiDrawLineJoinMiter: + cairo_set_line_join(c->cr, CAIRO_LINE_JOIN_MITER); + cairo_set_miter_limit(c->cr, p->MiterLimit); + break; + case uiDrawLineJoinRound: + cairo_set_line_join(c->cr, CAIRO_LINE_JOIN_ROUND); + break; + case uiDrawLineJoinBevel: + cairo_set_line_join(c->cr, CAIRO_LINE_JOIN_BEVEL); + break; + } + cairo_set_line_width(c->cr, p->Thickness); + cairo_set_dash(c->cr, p->Dashes, p->NumDashes, p->DashPhase); + cairo_stroke(c->cr); + cairo_pattern_destroy(pat); +} + +void uiDrawFill(uiDrawContext *c, uiDrawPath *path, uiDrawBrush *b) +{ + cairo_pattern_t *pat; + + uiprivRunPath(path, c->cr); + pat = mkbrush(b); + cairo_set_source(c->cr, pat); + switch (uiprivPathFillMode(path)) { + case uiDrawFillModeWinding: + cairo_set_fill_rule(c->cr, CAIRO_FILL_RULE_WINDING); + break; + case uiDrawFillModeAlternate: + cairo_set_fill_rule(c->cr, CAIRO_FILL_RULE_EVEN_ODD); + break; + } + cairo_fill(c->cr); + cairo_pattern_destroy(pat); +} + +void uiDrawTransform(uiDrawContext *c, uiDrawMatrix *m) +{ + cairo_matrix_t cm; + + uiprivM2C(m, &cm); + cairo_transform(c->cr, &cm); +} + +void uiDrawClip(uiDrawContext *c, uiDrawPath *path) +{ + uiprivRunPath(path, c->cr); + switch (uiprivPathFillMode(path)) { + case uiDrawFillModeWinding: + cairo_set_fill_rule(c->cr, CAIRO_FILL_RULE_WINDING); + break; + case uiDrawFillModeAlternate: + cairo_set_fill_rule(c->cr, CAIRO_FILL_RULE_EVEN_ODD); + break; + } + cairo_clip(c->cr); +} + +void uiDrawSave(uiDrawContext *c) +{ + cairo_save(c->cr); +} + +void uiDrawRestore(uiDrawContext *c) +{ + cairo_restore(c->cr); +} diff --git a/dep/libui/unix/draw.h b/dep/libui/unix/draw.h new file mode 100644 index 0000000..d46d074 --- /dev/null +++ b/dep/libui/unix/draw.h @@ -0,0 +1,14 @@ +// 5 may 2016 + +// draw.c +struct uiDrawContext { + cairo_t *cr; + GtkStyleContext *style; +}; + +// drawpath.c +extern void uiprivRunPath(uiDrawPath *p, cairo_t *cr); +extern uiDrawFillMode uiprivPathFillMode(uiDrawPath *path); + +// drawmatrix.c +extern void uiprivM2C(uiDrawMatrix *m, cairo_matrix_t *c); diff --git a/dep/libui/unix/drawmatrix.c b/dep/libui/unix/drawmatrix.c new file mode 100644 index 0000000..ffb4db3 --- /dev/null +++ b/dep/libui/unix/drawmatrix.c @@ -0,0 +1,115 @@ +// 6 september 2015 +#include "uipriv_unix.h" +#include "draw.h" + +static void m2c(uiDrawMatrix *m, cairo_matrix_t *c) +{ + c->xx = m->M11; + c->yx = m->M12; + c->xy = m->M21; + c->yy = m->M22; + c->x0 = m->M31; + c->y0 = m->M32; +} + +// needed by uiDrawTransform() +void uiprivM2C(uiDrawMatrix *m, cairo_matrix_t *c) +{ + m2c(m, c); +} + +static void c2m(cairo_matrix_t *c, uiDrawMatrix *m) +{ + m->M11 = c->xx; + m->M12 = c->yx; + m->M21 = c->xy; + m->M22 = c->yy; + m->M31 = c->x0; + m->M32 = c->y0; +} + +void uiDrawMatrixTranslate(uiDrawMatrix *m, double x, double y) +{ + cairo_matrix_t c; + + m2c(m, &c); + cairo_matrix_translate(&c, x, y); + c2m(&c, m); +} + +void uiDrawMatrixScale(uiDrawMatrix *m, double xCenter, double yCenter, double x, double y) +{ + cairo_matrix_t c; + double xt, yt; + + m2c(m, &c); + xt = x; + yt = y; + uiprivScaleCenter(xCenter, yCenter, &xt, &yt); + cairo_matrix_translate(&c, xt, yt); + cairo_matrix_scale(&c, x, y); + cairo_matrix_translate(&c, -xt, -yt); + c2m(&c, m); +} + +void uiDrawMatrixRotate(uiDrawMatrix *m, double x, double y, double amount) +{ + cairo_matrix_t c; + + m2c(m, &c); + cairo_matrix_translate(&c, x, y); + cairo_matrix_rotate(&c, amount); + cairo_matrix_translate(&c, -x, -y); + c2m(&c, m); +} + +void uiDrawMatrixSkew(uiDrawMatrix *m, double x, double y, double xamount, double yamount) +{ + uiprivFallbackSkew(m, x, y, xamount, yamount); +} + +void uiDrawMatrixMultiply(uiDrawMatrix *dest, uiDrawMatrix *src) +{ + cairo_matrix_t c; + cairo_matrix_t d; + + m2c(dest, &c); + m2c(src, &d); + cairo_matrix_multiply(&c, &c, &d); + c2m(&c, dest); +} + +int uiDrawMatrixInvertible(uiDrawMatrix *m) +{ + cairo_matrix_t c; + + m2c(m, &c); + return cairo_matrix_invert(&c) == CAIRO_STATUS_SUCCESS; +} + +int uiDrawMatrixInvert(uiDrawMatrix *m) +{ + cairo_matrix_t c; + + m2c(m, &c); + if (cairo_matrix_invert(&c) != CAIRO_STATUS_SUCCESS) + return 0; + c2m(&c, m); + return 1; +} + +void uiDrawMatrixTransformPoint(uiDrawMatrix *m, double *x, double *y) +{ + cairo_matrix_t c; + + m2c(m, &c); + cairo_matrix_transform_point(&c, x, y); +} + +void uiDrawMatrixTransformSize(uiDrawMatrix *m, double *x, double *y) +{ + cairo_matrix_t c; + + m2c(m, &c); + cairo_matrix_transform_distance(&c, x, y); +} diff --git a/dep/libui/unix/drawpath.c b/dep/libui/unix/drawpath.c new file mode 100644 index 0000000..045660f --- /dev/null +++ b/dep/libui/unix/drawpath.c @@ -0,0 +1,199 @@ +// 6 september 2015 +#include "uipriv_unix.h" +#include "draw.h" + +struct uiDrawPath { + GArray *pieces; + uiDrawFillMode fillMode; + gboolean ended; +}; + +struct piece { + int type; + double d[8]; + int b; +}; + +enum { + newFigure, + newFigureArc, + lineTo, + arcTo, + bezierTo, + closeFigure, + addRect, +}; + +uiDrawPath *uiDrawNewPath(uiDrawFillMode mode) +{ + uiDrawPath *p; + + p = uiprivNew(uiDrawPath); + p->pieces = g_array_new(FALSE, TRUE, sizeof (struct piece)); + p->fillMode = mode; + return p; +} + +void uiDrawFreePath(uiDrawPath *p) +{ + g_array_free(p->pieces, TRUE); + uiprivFree(p); +} + +static void add(uiDrawPath *p, struct piece *piece) +{ + if (p->ended) + uiprivUserBug("You cannot modify a uiDrawPath that has been ended. (path: %p)", p); + g_array_append_vals(p->pieces, piece, 1); +} + +void uiDrawPathNewFigure(uiDrawPath *p, double x, double y) +{ + struct piece piece; + + piece.type = newFigure; + piece.d[0] = x; + piece.d[1] = y; + add(p, &piece); +} + +void uiDrawPathNewFigureWithArc(uiDrawPath *p, double xCenter, double yCenter, double radius, double startAngle, double sweep, int negative) +{ + struct piece piece; + + if (sweep > 2 * uiPi) + sweep = 2 * uiPi; + piece.type = newFigureArc; + piece.d[0] = xCenter; + piece.d[1] = yCenter; + piece.d[2] = radius; + piece.d[3] = startAngle; + piece.d[4] = sweep; + piece.b = negative; + add(p, &piece); +} + +void uiDrawPathLineTo(uiDrawPath *p, double x, double y) +{ + struct piece piece; + + piece.type = lineTo; + piece.d[0] = x; + piece.d[1] = y; + add(p, &piece); +} + +void uiDrawPathArcTo(uiDrawPath *p, double xCenter, double yCenter, double radius, double startAngle, double sweep, int negative) +{ + struct piece piece; + + if (sweep > 2 * uiPi) + sweep = 2 * uiPi; + piece.type = arcTo; + piece.d[0] = xCenter; + piece.d[1] = yCenter; + piece.d[2] = radius; + piece.d[3] = startAngle; + piece.d[4] = sweep; + piece.b = negative; + add(p, &piece); +} + +void uiDrawPathBezierTo(uiDrawPath *p, double c1x, double c1y, double c2x, double c2y, double endX, double endY) +{ + struct piece piece; + + piece.type = bezierTo; + piece.d[0] = c1x; + piece.d[1] = c1y; + piece.d[2] = c2x; + piece.d[3] = c2y; + piece.d[4] = endX; + piece.d[5] = endY; + add(p, &piece); +} + +void uiDrawPathCloseFigure(uiDrawPath *p) +{ + struct piece piece; + + piece.type = closeFigure; + add(p, &piece); +} + +void uiDrawPathAddRectangle(uiDrawPath *p, double x, double y, double width, double height) +{ + struct piece piece; + + piece.type = addRect; + piece.d[0] = x; + piece.d[1] = y; + piece.d[2] = width; + piece.d[3] = height; + add(p, &piece); +} + +void uiDrawPathEnd(uiDrawPath *p) +{ + p->ended = TRUE; +} + +void uiprivRunPath(uiDrawPath *p, cairo_t *cr) +{ + guint i; + struct piece *piece; + void (*arc)(cairo_t *, double, double, double, double, double); + + if (!p->ended) + uiprivUserBug("You cannot draw with a uiDrawPath that has not been ended. (path: %p)", p); + cairo_new_path(cr); + for (i = 0; i < p->pieces->len; i++) { + piece = &g_array_index(p->pieces, struct piece, i); + switch (piece->type) { + case newFigure: + cairo_move_to(cr, piece->d[0], piece->d[1]); + break; + case newFigureArc: + cairo_new_sub_path(cr); + // fall through + case arcTo: + arc = cairo_arc; + if (piece->b) + arc = cairo_arc_negative; + (*arc)(cr, + piece->d[0], + piece->d[1], + piece->d[2], + piece->d[3], + piece->d[3] + piece->d[4]); + break; + case lineTo: + cairo_line_to(cr, piece->d[0], piece->d[1]); + break; + case bezierTo: + cairo_curve_to(cr, + piece->d[0], + piece->d[1], + piece->d[2], + piece->d[3], + piece->d[4], + piece->d[5]); + break; + case closeFigure: + cairo_close_path(cr); + break; + case addRect: + cairo_rectangle(cr, + piece->d[0], + piece->d[1], + piece->d[2], + piece->d[3]); + break; + } + } +} + +uiDrawFillMode uiprivPathFillMode(uiDrawPath *path) +{ + return path->fillMode; +} diff --git a/dep/libui/unix/drawtext.c b/dep/libui/unix/drawtext.c new file mode 100644 index 0000000..477e9ca --- /dev/null +++ b/dep/libui/unix/drawtext.c @@ -0,0 +1,81 @@ +// 11 march 2018 +#include "uipriv_unix.h" +#include "draw.h" +#include "attrstr.h" + +struct uiDrawTextLayout { + PangoLayout *layout; +}; + +// we need a context for a few things +// the documentation suggests creating cairo_t-specific, GdkScreen-specific, or even GtkWidget-specific contexts, but we can't really do that because we want our uiDrawTextFonts and uiDrawTextLayouts to be context-independent +// we could use pango_font_map_create_context(pango_cairo_font_map_get_default()) but that will ignore GDK-specific settings +// so let's use gdk_pango_context_get() instead; even though it's for the default screen only, it's good enough for us +#define mkGenericPangoCairoContext() (gdk_pango_context_get()) + +static const PangoAlignment pangoAligns[] = { + [uiDrawTextAlignLeft] = PANGO_ALIGN_LEFT, + [uiDrawTextAlignCenter] = PANGO_ALIGN_CENTER, + [uiDrawTextAlignRight] = PANGO_ALIGN_RIGHT, +}; + +uiDrawTextLayout *uiDrawNewTextLayout(uiDrawTextLayoutParams *p) +{ + uiDrawTextLayout *tl; + PangoContext *context; + PangoFontDescription *desc; + PangoAttrList *attrs; + int pangoWidth; + + tl = uiprivNew(uiDrawTextLayout); + + // in this case, the context is necessary to create the layout + // the layout takes a ref on the context so we can unref it afterward + context = mkGenericPangoCairoContext(); + tl->layout = pango_layout_new(context); + g_object_unref(context); + + // this is safe; pango_layout_set_text() copies the string + pango_layout_set_text(tl->layout, uiAttributedStringString(p->String), -1); + + desc = uiprivFontDescriptorToPangoFontDescription(p->DefaultFont); + pango_layout_set_font_description(tl->layout, desc); + // this is safe; the description is copied + pango_font_description_free(desc); + + pangoWidth = cairoToPango(p->Width); + if (p->Width < 0) + pangoWidth = -1; + pango_layout_set_width(tl->layout, pangoWidth); + + pango_layout_set_alignment(tl->layout, pangoAligns[p->Align]); + + attrs = uiprivAttributedStringToPangoAttrList(p); + pango_layout_set_attributes(tl->layout, attrs); + pango_attr_list_unref(attrs); + + return tl; +} + +void uiDrawFreeTextLayout(uiDrawTextLayout *tl) +{ + g_object_unref(tl->layout); + uiprivFree(tl); +} + +void uiDrawText(uiDrawContext *c, uiDrawTextLayout *tl, double x, double y) +{ + // TODO have an implicit save/restore on each drawing functions instead? and is this correct? + cairo_set_source_rgb(c->cr, 0.0, 0.0, 0.0); + cairo_move_to(c->cr, x, y); + pango_cairo_show_layout(c->cr, tl->layout); +} + +void uiDrawTextLayoutExtents(uiDrawTextLayout *tl, double *width, double *height) +{ + PangoRectangle logical; + + pango_layout_get_extents(tl->layout, NULL, &logical); + *width = pangoToCairo(logical.width); + *height = pangoToCairo(logical.height); +} diff --git a/dep/libui/unix/editablecombo.c b/dep/libui/unix/editablecombo.c new file mode 100644 index 0000000..7ee3829 --- /dev/null +++ b/dep/libui/unix/editablecombo.c @@ -0,0 +1,79 @@ +// 11 june 2015 +#include "uipriv_unix.h" + +struct uiEditableCombobox { + uiUnixControl c; + GtkWidget *widget; + GtkBin *bin; + GtkComboBox *combobox; + GtkComboBoxText *comboboxText; + void (*onChanged)(uiEditableCombobox *, void *); + void *onChangedData; + gulong onChangedSignal; +}; + +uiUnixControlAllDefaults(uiEditableCombobox) + +static void onChanged(GtkComboBox *cbox, gpointer data) +{ + uiEditableCombobox *c = uiEditableCombobox(data); + + (*(c->onChanged))(c, c->onChangedData); +} + +static void defaultOnChanged(uiEditableCombobox *c, void *data) +{ + // do nothing +} + +void uiEditableComboboxAppend(uiEditableCombobox *c, const char *text) +{ + gtk_combo_box_text_append(c->comboboxText, NULL, text); +} + +char *uiEditableComboboxText(uiEditableCombobox *c) +{ + char *s; + char *out; + + s = gtk_combo_box_text_get_active_text(c->comboboxText); + // s will always be non-NULL in the case of a combobox with an entry (according to the source code) + out = uiUnixStrdupText(s); + g_free(s); + return out; +} + +void uiEditableComboboxSetText(uiEditableCombobox *c, const char *text) +{ + GtkEntry *e; + + // we need to inhibit sending of ::changed because this WILL send a ::changed otherwise + g_signal_handler_block(c->combobox, c->onChangedSignal); + // since there isn't a gtk_combo_box_text_set_active_text()... + e = GTK_ENTRY(gtk_bin_get_child(c->bin)); + gtk_entry_set_text(e, text); + g_signal_handler_unblock(c->combobox, c->onChangedSignal); +} + +void uiEditableComboboxOnChanged(uiEditableCombobox *c, void (*f)(uiEditableCombobox *c, void *data), void *data) +{ + c->onChanged = f; + c->onChangedData = data; +} + +uiEditableCombobox *uiNewEditableCombobox(void) +{ + uiEditableCombobox *c; + + uiUnixNewControl(uiEditableCombobox, c); + + c->widget = gtk_combo_box_text_new_with_entry(); + c->bin = GTK_BIN(c->widget); + c->combobox = GTK_COMBO_BOX(c->widget); + c->comboboxText = GTK_COMBO_BOX_TEXT(c->widget); + + c->onChangedSignal = g_signal_connect(c->widget, "changed", G_CALLBACK(onChanged), c); + uiEditableComboboxOnChanged(c, defaultOnChanged, NULL); + + return c; +} diff --git a/dep/libui/unix/entry.c b/dep/libui/unix/entry.c new file mode 100644 index 0000000..4a9a1d0 --- /dev/null +++ b/dep/libui/unix/entry.c @@ -0,0 +1,97 @@ +// 11 june 2015 +#include "uipriv_unix.h" + +struct uiEntry { + uiUnixControl c; + GtkWidget *widget; + GtkEntry *entry; + GtkEditable *editable; + void (*onChanged)(uiEntry *, void *); + void *onChangedData; + gulong onChangedSignal; +}; + +uiUnixControlAllDefaults(uiEntry) + +static void onChanged(GtkEditable *editable, gpointer data) +{ + uiEntry *e = uiEntry(data); + + (*(e->onChanged))(e, e->onChangedData); +} + +static void defaultOnChanged(uiEntry *e, void *data) +{ + // do nothing +} + +char *uiEntryText(uiEntry *e) +{ + return uiUnixStrdupText(gtk_entry_get_text(e->entry)); +} + +void uiEntrySetText(uiEntry *e, const char *text) +{ + // we need to inhibit sending of ::changed because this WILL send a ::changed otherwise + g_signal_handler_block(e->editable, e->onChangedSignal); + gtk_entry_set_text(e->entry, text); + g_signal_handler_unblock(e->editable, e->onChangedSignal); + // don't queue the control for resize; entry sizes are independent of their contents +} + +void uiEntryOnChanged(uiEntry *e, void (*f)(uiEntry *, void *), void *data) +{ + e->onChanged = f; + e->onChangedData = data; +} + +int uiEntryReadOnly(uiEntry *e) +{ + return gtk_editable_get_editable(e->editable) == FALSE; +} + +void uiEntrySetReadOnly(uiEntry *e, int readonly) +{ + gboolean editable; + + editable = TRUE; + if (readonly) + editable = FALSE; + gtk_editable_set_editable(e->editable, editable); +} + +static uiEntry *finishNewEntry(GtkWidget *w, const gchar *signal) +{ + uiEntry *e; + + uiUnixNewControl(uiEntry, e); + + e->widget = w; + e->entry = GTK_ENTRY(e->widget); + e->editable = GTK_EDITABLE(e->widget); + + e->onChangedSignal = g_signal_connect(e->widget, signal, G_CALLBACK(onChanged), e); + uiEntryOnChanged(e, defaultOnChanged, NULL); + + return e; +} + +uiEntry *uiNewEntry(void) +{ + return finishNewEntry(gtk_entry_new(), "changed"); +} + +uiEntry *uiNewPasswordEntry(void) +{ + GtkWidget *e; + + e = gtk_entry_new(); + gtk_entry_set_visibility(GTK_ENTRY(e), FALSE); + return finishNewEntry(e, "changed"); +} + +// TODO make it use a separate function to be type-safe +uiEntry *uiNewSearchEntry(void) +{ + return finishNewEntry(gtk_search_entry_new(), "search-changed"); +} diff --git a/dep/libui/unix/fontbutton.c b/dep/libui/unix/fontbutton.c new file mode 100644 index 0000000..d239952 --- /dev/null +++ b/dep/libui/unix/fontbutton.c @@ -0,0 +1,75 @@ +// 14 april 2016 +#include "uipriv_unix.h" +#include "attrstr.h" + +struct uiFontButton { + uiUnixControl c; + GtkWidget *widget; + GtkButton *button; + GtkFontButton *fb; + GtkFontChooser *fc; + void (*onChanged)(uiFontButton *, void *); + void *onChangedData; +}; + +uiUnixControlAllDefaults(uiFontButton) + +// TODO NOTE no need to inhibit the signal; font-set is documented as only being sent when the user changes the font +static void onFontSet(GtkFontButton *button, gpointer data) +{ + uiFontButton *b = uiFontButton(data); + + (*(b->onChanged))(b, b->onChangedData); +} + +static void defaultOnChanged(uiFontButton *b, void *data) +{ + // do nothing +} + +void uiFontButtonFont(uiFontButton *b, uiFontDescriptor *desc) +{ + PangoFontDescription *pdesc; + + pdesc = gtk_font_chooser_get_font_desc(b->fc); + uiprivFontDescriptorFromPangoFontDescription(pdesc, desc); + // pdesc is transfer-full and thus is a copy + pango_font_description_free(pdesc); +} + +void uiFontButtonOnChanged(uiFontButton *b, void (*f)(uiFontButton *, void *), void *data) +{ + b->onChanged = f; + b->onChangedData = data; +} + +uiFontButton *uiNewFontButton(void) +{ + uiFontButton *b; + + uiUnixNewControl(uiFontButton, b); + + b->widget = gtk_font_button_new(); + b->button = GTK_BUTTON(b->widget); + b->fb = GTK_FONT_BUTTON(b->widget); + b->fc = GTK_FONT_CHOOSER(b->widget); + + // match behavior on other platforms + gtk_font_button_set_show_style(b->fb, TRUE); + gtk_font_button_set_show_size(b->fb, TRUE); + gtk_font_button_set_use_font(b->fb, FALSE); + gtk_font_button_set_use_size(b->fb, FALSE); + // other customizations + gtk_font_chooser_set_show_preview_entry(b->fc, TRUE); + + g_signal_connect(b->widget, "font-set", G_CALLBACK(onFontSet), b); + uiFontButtonOnChanged(b, defaultOnChanged, NULL); + + return b; +} + +void uiFreeFontButtonFont(uiFontDescriptor *desc) +{ + // TODO ensure this is synchronized with fontmatch.c + uiFreeText((char *) (desc->Family)); +} diff --git a/dep/libui/unix/fontmatch.c b/dep/libui/unix/fontmatch.c new file mode 100644 index 0000000..95f4fdd --- /dev/null +++ b/dep/libui/unix/fontmatch.c @@ -0,0 +1,76 @@ +// 11 march 2018 +#include "uipriv_unix.h" +#include "attrstr.h" + +static const PangoStyle pangoItalics[] = { + [uiTextItalicNormal] = PANGO_STYLE_NORMAL, + [uiTextItalicOblique] = PANGO_STYLE_OBLIQUE, + [uiTextItalicItalic] = PANGO_STYLE_ITALIC, +}; + +static const PangoStretch pangoStretches[] = { + [uiTextStretchUltraCondensed] = PANGO_STRETCH_ULTRA_CONDENSED, + [uiTextStretchExtraCondensed] = PANGO_STRETCH_EXTRA_CONDENSED, + [uiTextStretchCondensed] = PANGO_STRETCH_CONDENSED, + [uiTextStretchSemiCondensed] = PANGO_STRETCH_SEMI_CONDENSED, + [uiTextStretchNormal] = PANGO_STRETCH_NORMAL, + [uiTextStretchSemiExpanded] = PANGO_STRETCH_SEMI_EXPANDED, + [uiTextStretchExpanded] = PANGO_STRETCH_EXPANDED, + [uiTextStretchExtraExpanded] = PANGO_STRETCH_EXTRA_EXPANDED, + [uiTextStretchUltraExpanded] = PANGO_STRETCH_ULTRA_EXPANDED, +}; + +// for the most part, pango weights correlate to ours +// the differences: +// - Book — libui: 350, Pango: 380 +// - Ultra Heavy — libui: 950, Pango: 1000 +// TODO figure out what to do about this misalignment +PangoWeight uiprivWeightToPangoWeight(uiTextWeight w) +{ + return (PangoWeight) w; +} + +PangoStyle uiprivItalicToPangoStyle(uiTextItalic i) +{ + return pangoItalics[i]; +} + +PangoStretch uiprivStretchToPangoStretch(uiTextStretch s) +{ + return pangoStretches[s]; +} + +PangoFontDescription *uiprivFontDescriptorToPangoFontDescription(const uiFontDescriptor *uidesc) +{ + PangoFontDescription *desc; + + desc = pango_font_description_new(); + pango_font_description_set_family(desc, uidesc->Family); + // see https://developer.gnome.org/pango/1.30/pango-Fonts.html#pango-font-description-set-size and https://developer.gnome.org/pango/1.30/pango-Glyph-Storage.html#pango-units-from-double + pango_font_description_set_size(desc, pango_units_from_double(uidesc->Size)); + pango_font_description_set_weight(desc, uiprivWeightToPangoWeight(uidesc->Weight)); + pango_font_description_set_style(desc, uiprivItalicToPangoStyle(uidesc->Italic)); + pango_font_description_set_stretch(desc, uiprivStretchToPangoStretch(uidesc->Stretch)); + return desc; +} + +void uiprivFontDescriptorFromPangoFontDescription(PangoFontDescription *pdesc, uiFontDescriptor *uidesc) +{ + PangoStyle pitalic; + PangoStretch pstretch; + + uidesc->Family = uiUnixStrdupText(pango_font_description_get_family(pdesc)); + pitalic = pango_font_description_get_style(pdesc); + // TODO reverse the above misalignment if it is corrected + uidesc->Weight = pango_font_description_get_weight(pdesc); + pstretch = pango_font_description_get_stretch(pdesc); + // absolute size does not matter because, as above, 1 device unit == 1 cairo point + uidesc->Size = pango_units_to_double(pango_font_description_get_size(pdesc)); + + for (uidesc->Italic = uiTextItalicNormal; uidesc->Italic < uiTextItalicItalic; uidesc->Italic++) + if (pangoItalics[uidesc->Italic] == pitalic) + break; + for (uidesc->Stretch = uiTextStretchUltraCondensed; uidesc->Stretch < uiTextStretchUltraExpanded; uidesc->Stretch++) + if (pangoStretches[uidesc->Stretch] == pstretch) + break; +} diff --git a/dep/libui/unix/form.c b/dep/libui/unix/form.c new file mode 100644 index 0000000..36ad77d --- /dev/null +++ b/dep/libui/unix/form.c @@ -0,0 +1,159 @@ +// 8 june 2016 +#include "uipriv_unix.h" + +struct formChild { + uiControl *c; + int stretchy; + GtkWidget *label; + gboolean oldhexpand; + GtkAlign oldhalign; + gboolean oldvexpand; + GtkAlign oldvalign; + GBinding *labelBinding; +}; + +struct uiForm { + uiUnixControl c; + GtkWidget *widget; + GtkContainer *container; + GtkGrid *grid; + GArray *children; + int padded; + GtkSizeGroup *stretchygroup; // ensures all stretchy controls have the same size +}; + +uiUnixControlAllDefaultsExceptDestroy(uiForm) + +#define ctrl(f, i) &g_array_index(f->children, struct formChild, i) + +static void uiFormDestroy(uiControl *c) +{ + uiForm *f = uiForm(c); + struct formChild *fc; + guint i; + + // kill the size group + g_object_unref(f->stretchygroup); + // free all controls + for (i = 0; i < f->children->len; i++) { + fc = ctrl(f, i); + uiControlSetParent(fc->c, NULL); + uiUnixControlSetContainer(uiUnixControl(fc->c), f->container, TRUE); + uiControlDestroy(fc->c); + gtk_widget_destroy(fc->label); + } + g_array_free(f->children, TRUE); + // and then ourselves + g_object_unref(f->widget); + uiFreeControl(uiControl(f)); +} + +void uiFormAppend(uiForm *f, const char *label, uiControl *c, int stretchy) +{ + struct formChild fc; + GtkWidget *widget; + guint row; + + fc.c = c; + widget = GTK_WIDGET(uiControlHandle(fc.c)); + fc.stretchy = stretchy; + fc.oldhexpand = gtk_widget_get_hexpand(widget); + fc.oldhalign = gtk_widget_get_halign(widget); + fc.oldvexpand = gtk_widget_get_vexpand(widget); + fc.oldvalign = gtk_widget_get_valign(widget); + + if (stretchy) { + gtk_widget_set_vexpand(widget, TRUE); + gtk_widget_set_valign(widget, GTK_ALIGN_FILL); + gtk_size_group_add_widget(f->stretchygroup, widget); + } else + gtk_widget_set_vexpand(widget, FALSE); + // and make them fill horizontally + gtk_widget_set_hexpand(widget, TRUE); + gtk_widget_set_halign(widget, GTK_ALIGN_FILL); + + fc.label = gtk_label_new(label); + gtk_widget_set_hexpand(fc.label, FALSE); + gtk_widget_set_halign(fc.label, GTK_ALIGN_END); + gtk_widget_set_vexpand(fc.label, FALSE); + if (GTK_IS_SCROLLED_WINDOW(widget)) + gtk_widget_set_valign(fc.label, GTK_ALIGN_START); + else + gtk_widget_set_valign(fc.label, GTK_ALIGN_CENTER); + gtk_style_context_add_class(gtk_widget_get_style_context(fc.label), "dim-label"); + row = f->children->len; + gtk_grid_attach(f->grid, fc.label, + 0, row, + 1, 1); + // and make them share visibility so if the control is hidden, so is its label + fc.labelBinding = g_object_bind_property(GTK_WIDGET(uiControlHandle(fc.c)), "visible", + fc.label, "visible", + G_BINDING_SYNC_CREATE); + + uiControlSetParent(fc.c, uiControl(f)); + uiUnixControlSetContainer(uiUnixControl(fc.c), f->container, FALSE); + g_array_append_val(f->children, fc); + + // move the widget to the correct place + gtk_container_child_set(f->container, widget, + "left-attach", 1, + "top-attach", row, + NULL); +} + +void uiFormDelete(uiForm *f, int index) +{ + struct formChild *fc; + GtkWidget *widget; + + fc = ctrl(f, index); + widget = GTK_WIDGET(uiControlHandle(fc->c)); + + gtk_widget_destroy(fc->label); + + uiControlSetParent(fc->c, NULL); + uiUnixControlSetContainer(uiUnixControl(fc->c), f->container, TRUE); + + if (fc->stretchy) + gtk_size_group_remove_widget(f->stretchygroup, widget); + gtk_widget_set_hexpand(widget, fc->oldhexpand); + gtk_widget_set_halign(widget, fc->oldhalign); + gtk_widget_set_vexpand(widget, fc->oldvexpand); + gtk_widget_set_valign(widget, fc->oldvalign); + + g_array_remove_index(f->children, index); +} + +int uiFormPadded(uiForm *f) +{ + return f->padded; +} + +void uiFormSetPadded(uiForm *f, int padded) +{ + f->padded = padded; + if (f->padded) { + gtk_grid_set_row_spacing(f->grid, uiprivGTKYPadding); + gtk_grid_set_column_spacing(f->grid, uiprivGTKXPadding); + } else { + gtk_grid_set_row_spacing(f->grid, 0); + gtk_grid_set_column_spacing(f->grid, 0); + } +} + +uiForm *uiNewForm(void) +{ + uiForm *f; + + uiUnixNewControl(uiForm, f); + + f->widget = gtk_grid_new(); + f->container = GTK_CONTAINER(f->widget); + f->grid = GTK_GRID(f->widget); + + f->stretchygroup = gtk_size_group_new(GTK_SIZE_GROUP_VERTICAL); + + f->children = g_array_new(FALSE, TRUE, sizeof (struct formChild)); + + return f; +} diff --git a/dep/libui/unix/future.c b/dep/libui/unix/future.c new file mode 100644 index 0000000..475dbc1 --- /dev/null +++ b/dep/libui/unix/future.c @@ -0,0 +1,60 @@ +// 29 june 2016 +#include "uipriv_unix.h" + +// functions FROM THE FUTURE! +// in some cases, because being held back by LTS releases sucks :/ +// in others, because parts of GTK+ being unstable until recently also sucks :/ + +// added in pango 1.38; we need 1.36 +static PangoAttribute *(*newFeaturesAttr)(const gchar *features) = NULL; +static PangoAttribute *(*newFGAlphaAttr)(guint16 alpha) = NULL; +static PangoAttribute *(*newBGAlphaAttr)(guint16 alpha) = NULL; + +// added in GTK+ 3.20; we need 3.10 +static void (*gwpIterSetObjectName)(GtkWidgetPath *path, gint pos, const char *name) = NULL; + +// note that we treat any error as "the symbols aren't there" (and don't care if dlclose() failed) +void uiprivLoadFutures(void) +{ + void *handle; + + // dlsym() walks the dependency chain, so opening the current process should be sufficient + handle = dlopen(NULL, RTLD_LAZY); + if (handle == NULL) + return; +#define GET(var, fn) *((void **) (&var)) = dlsym(handle, #fn) + GET(newFeaturesAttr, pango_attr_font_features_new); + GET(newFGAlphaAttr, pango_attr_foreground_alpha_new); + GET(newBGAlphaAttr, pango_attr_background_alpha_new); + GET(gwpIterSetObjectName, gtk_widget_path_iter_set_object_name); + dlclose(handle); +} + +PangoAttribute *uiprivFUTURE_pango_attr_font_features_new(const gchar *features) +{ + if (newFeaturesAttr == NULL) + return NULL; + return (*newFeaturesAttr)(features); +} + +PangoAttribute *uiprivFUTURE_pango_attr_foreground_alpha_new(guint16 alpha) +{ + if (newFGAlphaAttr == NULL) + return NULL; + return (*newFGAlphaAttr)(alpha); +} + +PangoAttribute *uiprivFUTURE_pango_attr_background_alpha_new(guint16 alpha) +{ + if (newBGAlphaAttr == NULL) + return NULL; + return (*newBGAlphaAttr)(alpha); +} + +gboolean uiprivFUTURE_gtk_widget_path_iter_set_object_name(GtkWidgetPath *path, gint pos, const char *name) +{ + if (gwpIterSetObjectName == NULL) + return FALSE; + (*gwpIterSetObjectName)(path, pos, name); + return TRUE; +} diff --git a/dep/libui/unix/graphemes.c b/dep/libui/unix/graphemes.c new file mode 100644 index 0000000..952f1ef --- /dev/null +++ b/dep/libui/unix/graphemes.c @@ -0,0 +1,63 @@ +// 25 may 2016 +#include "uipriv_unix.h" +#include "attrstr.h" + +int uiprivGraphemesTakesUTF16(void) +{ + return 0; +} + +uiprivGraphemes *uiprivNewGraphemes(void *s, size_t len) +{ + uiprivGraphemes *g; + char *text = (char *) s; + size_t lenchars; + PangoLogAttr *logattrs; + size_t i; + size_t *op; + + g = uiprivNew(uiprivGraphemes); + + // TODO see if we can use the utf routines + lenchars = g_utf8_strlen(text, -1); + logattrs = (PangoLogAttr *) uiprivAlloc((lenchars + 1) * sizeof (PangoLogAttr), "PangoLogAttr[] (graphemes)"); + pango_get_log_attrs(text, len, + -1, NULL, + logattrs, lenchars + 1); + + // first figure out how many graphemes there are + g->len = 0; + for (i = 0; i < lenchars; i++) + if (logattrs[i].is_cursor_position != 0) + g->len++; + + g->pointsToGraphemes = (size_t *) uiprivAlloc((len + 1) * sizeof (size_t), "size_t[] (graphemes)"); + g->graphemesToPoints = (size_t *) uiprivAlloc((g->len + 1) * sizeof (size_t), "size_t[] (graphemes)"); + + // compute the graphemesToPoints array + // TODO merge with the next for loop somehow? + op = g->graphemesToPoints; + for (i = 0; i < lenchars; i++) + if (logattrs[i].is_cursor_position != 0) + // TODO optimize this + *op++ = g_utf8_offset_to_pointer(text, i) - text; + // and do the last one + *op++ = len; + + // and finally build the pointsToGraphemes array + op = g->pointsToGraphemes; + for (i = 0; i < g->len; i++) { + size_t j; + size_t first, last; + + first = g->graphemesToPoints[i]; + last = g->graphemesToPoints[i + 1]; + for (j = first; j < last; j++) + *op++ = i; + } + // and do the last one + *op++ = i; + + uiprivFree(logattrs); + return g; +} diff --git a/dep/libui/unix/grid.c b/dep/libui/unix/grid.c new file mode 100644 index 0000000..7759cec --- /dev/null +++ b/dep/libui/unix/grid.c @@ -0,0 +1,141 @@ +// 9 june 2016 +#include "uipriv_unix.h" + +struct gridChild { + uiControl *c; + GtkWidget *label; + gboolean oldhexpand; + GtkAlign oldhalign; + gboolean oldvexpand; + GtkAlign oldvalign; +}; + +struct uiGrid { + uiUnixControl c; + GtkWidget *widget; + GtkContainer *container; + GtkGrid *grid; + GArray *children; + int padded; +}; + +uiUnixControlAllDefaultsExceptDestroy(uiGrid) + +#define ctrl(g, i) &g_array_index(g->children, struct gridChild, i) + +static void uiGridDestroy(uiControl *c) +{ + uiGrid *g = uiGrid(c); + struct gridChild *gc; + guint i; + + // free all controls + for (i = 0; i < g->children->len; i++) { + gc = ctrl(g, i); + uiControlSetParent(gc->c, NULL); + uiUnixControlSetContainer(uiUnixControl(gc->c), g->container, TRUE); + uiControlDestroy(gc->c); + } + g_array_free(g->children, TRUE); + // and then ourselves + g_object_unref(g->widget); + uiFreeControl(uiControl(g)); +} + +#define TODO_MASSIVE_HACK(c) \ + if (!uiUnixControl(c)->addedBefore) { \ + g_object_ref_sink(GTK_WIDGET(uiControlHandle(uiControl(c)))); \ + gtk_widget_show(GTK_WIDGET(uiControlHandle(uiControl(c)))); \ + uiUnixControl(c)->addedBefore = TRUE; \ + } + +static const GtkAlign gtkAligns[] = { + [uiAlignFill] = GTK_ALIGN_FILL, + [uiAlignStart] = GTK_ALIGN_START, + [uiAlignCenter] = GTK_ALIGN_CENTER, + [uiAlignEnd] = GTK_ALIGN_END, +}; + +static const GtkPositionType gtkPositions[] = { + [uiAtLeading] = GTK_POS_LEFT, + [uiAtTop] = GTK_POS_TOP, + [uiAtTrailing] = GTK_POS_RIGHT, + [uiAtBottom] = GTK_POS_BOTTOM, +}; + +static GtkWidget *prepare(struct gridChild *gc, uiControl *c, int hexpand, uiAlign halign, int vexpand, uiAlign valign) +{ + GtkWidget *widget; + + gc->c = c; + widget = GTK_WIDGET(uiControlHandle(gc->c)); + gc->oldhexpand = gtk_widget_get_hexpand(widget); + gc->oldhalign = gtk_widget_get_halign(widget); + gc->oldvexpand = gtk_widget_get_vexpand(widget); + gc->oldvalign = gtk_widget_get_valign(widget); + gtk_widget_set_hexpand(widget, hexpand != 0); + gtk_widget_set_halign(widget, gtkAligns[halign]); + gtk_widget_set_vexpand(widget, vexpand != 0); + gtk_widget_set_valign(widget, gtkAligns[valign]); + return widget; +} + +void uiGridAppend(uiGrid *g, uiControl *c, int left, int top, int xspan, int yspan, int hexpand, uiAlign halign, int vexpand, uiAlign valign) +{ + struct gridChild gc; + GtkWidget *widget; + + widget = prepare(&gc, c, hexpand, halign, vexpand, valign); + uiControlSetParent(gc.c, uiControl(g)); + TODO_MASSIVE_HACK(uiUnixControl(gc.c)); + gtk_grid_attach(g->grid, widget, + left, top, + xspan, yspan); + g_array_append_val(g->children, gc); +} + +void uiGridInsertAt(uiGrid *g, uiControl *c, uiControl *existing, uiAt at, int xspan, int yspan, int hexpand, uiAlign halign, int vexpand, uiAlign valign) +{ + struct gridChild gc; + GtkWidget *widget; + + widget = prepare(&gc, c, hexpand, halign, vexpand, valign); + uiControlSetParent(gc.c, uiControl(g)); + TODO_MASSIVE_HACK(uiUnixControl(gc.c)); + gtk_grid_attach_next_to(g->grid, widget, + GTK_WIDGET(uiControlHandle(existing)), gtkPositions[at], + xspan, yspan); + g_array_append_val(g->children, gc); +} + +int uiGridPadded(uiGrid *g) +{ + return g->padded; +} + +void uiGridSetPadded(uiGrid *g, int padded) +{ + g->padded = padded; + if (g->padded) { + gtk_grid_set_row_spacing(g->grid, uiprivGTKYPadding); + gtk_grid_set_column_spacing(g->grid, uiprivGTKXPadding); + } else { + gtk_grid_set_row_spacing(g->grid, 0); + gtk_grid_set_column_spacing(g->grid, 0); + } +} + +uiGrid *uiNewGrid(void) +{ + uiGrid *g; + + uiUnixNewControl(uiGrid, g); + + g->widget = gtk_grid_new(); + g->container = GTK_CONTAINER(g->widget); + g->grid = GTK_GRID(g->widget); + + g->children = g_array_new(FALSE, TRUE, sizeof (struct gridChild)); + + return g; +} diff --git a/dep/libui/unix/group.c b/dep/libui/unix/group.c new file mode 100644 index 0000000..545c712 --- /dev/null +++ b/dep/libui/unix/group.c @@ -0,0 +1,89 @@ +// 11 june 2015 +#include "uipriv_unix.h" + +struct uiGroup { + uiUnixControl c; + GtkWidget *widget; + GtkContainer *container; + GtkBin *bin; + GtkFrame *frame; + + // unfortunately, even though a GtkFrame is a GtkBin, calling gtk_container_set_border_width() on it /includes/ the GtkFrame's label; we don't want that + uiprivChild *child; + + int margined; +}; + +uiUnixControlAllDefaultsExceptDestroy(uiGroup) + +static void uiGroupDestroy(uiControl *c) +{ + uiGroup *g = uiGroup(c); + + if (g->child != NULL) + uiprivChildDestroy(g->child); + g_object_unref(g->widget); + uiFreeControl(uiControl(g)); +} + +char *uiGroupTitle(uiGroup *g) +{ + return uiUnixStrdupText(gtk_frame_get_label(g->frame)); +} + +void uiGroupSetTitle(uiGroup *g, const char *text) +{ + gtk_frame_set_label(g->frame, text); +} + +void uiGroupSetChild(uiGroup *g, uiControl *child) +{ + if (g->child != NULL) + uiprivChildRemove(g->child); + g->child = uiprivNewChildWithBox(child, uiControl(g), g->container, g->margined); +} + +int uiGroupMargined(uiGroup *g) +{ + return g->margined; +} + +void uiGroupSetMargined(uiGroup *g, int margined) +{ + g->margined = margined; + if (g->child != NULL) + uiprivChildSetMargined(g->child, g->margined); +} + +uiGroup *uiNewGroup(const char *text) +{ + uiGroup *g; + gfloat yalign; + GtkLabel *label; + PangoAttribute *bold; + PangoAttrList *boldlist; + + uiUnixNewControl(uiGroup, g); + + g->widget = gtk_frame_new(text); + g->container = GTK_CONTAINER(g->widget); + g->bin = GTK_BIN(g->widget); + g->frame = GTK_FRAME(g->widget); + + // with GTK+, groupboxes by default have frames and slightly x-offset regular text + // they should have no frame and fully left-justified, bold text + // preserve default y-alignment + gtk_frame_get_label_align(g->frame, NULL, &yalign); + gtk_frame_set_label_align(g->frame, 0, yalign); + gtk_frame_set_shadow_type(g->frame, GTK_SHADOW_NONE); + label = GTK_LABEL(gtk_frame_get_label_widget(g->frame)); + // this is the boldness level used by GtkPrintUnixDialog + // (it technically uses "bold" but see pango's pango-enum-types.c for the name conversion; GType is weird) + bold = pango_attr_weight_new(PANGO_WEIGHT_BOLD); + boldlist = pango_attr_list_new(); + pango_attr_list_insert(boldlist, bold); + gtk_label_set_attributes(label, boldlist); + pango_attr_list_unref(boldlist); // thanks baedert in irc.gimp.net/#gtk+ + + return g; +} diff --git a/dep/libui/unix/image.c b/dep/libui/unix/image.c new file mode 100644 index 0000000..cf21900 --- /dev/null +++ b/dep/libui/unix/image.c @@ -0,0 +1,134 @@ +// 27 june 2016 +#include "uipriv_unix.h" + +struct uiImage { + double width; + double height; + GPtrArray *images; +}; + +static void freeImageRep(gpointer item) +{ + cairo_surface_t *cs = (cairo_surface_t *) item; + + cairo_surface_destroy(cs); +} + +uiImage *uiNewImage(double width, double height) +{ + uiImage *i; + + i = uiprivNew(uiImage); + i->width = width; + i->height = height; + i->images = g_ptr_array_new_with_free_func(freeImageRep); + return i; +} + +void uiFreeImage(uiImage *i) +{ + g_ptr_array_free(i->images, TRUE); + uiprivFree(i); +} + +void uiImageAppend(uiImage *i, void *pixels, int pixelWidth, int pixelHeight, int byteStride) +{ + cairo_surface_t *cs; + uint8_t *data, *pix; + int realStride; + int x, y; + + // note that this is native-endian + cs = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, + pixelWidth, pixelHeight); + if (cairo_surface_status(cs) != CAIRO_STATUS_SUCCESS) + /* TODO */; + cairo_surface_flush(cs); + + pix = (uint8_t *) pixels; + data = (uint8_t *) cairo_image_surface_get_data(cs); + realStride = cairo_image_surface_get_stride(cs); + for (y = 0; y < pixelHeight; y++) { + for (x = 0; x < pixelWidth * 4; x += 4) { + union { + uint32_t v32; + uint8_t v8[4]; + } v; + + v.v32 = ((uint32_t) (pix[x + 3])) << 24; + v.v32 |= ((uint32_t) (pix[x])) << 16; + v.v32 |= ((uint32_t) (pix[x + 1])) << 8; + v.v32 |= ((uint32_t) (pix[x + 2])); + data[x] = v.v8[0]; + data[x + 1] = v.v8[1]; + data[x + 2] = v.v8[2]; + data[x + 3] = v.v8[3]; + } + pix += byteStride; + data += realStride; + } + + cairo_surface_mark_dirty(cs); + g_ptr_array_add(i->images, cs); +} + +struct matcher { + cairo_surface_t *best; + int distX; + int distY; + int targetX; + int targetY; + gboolean foundLarger; +}; + +// TODO is this the right algorithm? +static void match(gpointer surface, gpointer data) +{ + cairo_surface_t *cs = (cairo_surface_t *) surface; + struct matcher *m = (struct matcher *) data; + int x, y; + int x2, y2; + + x = cairo_image_surface_get_width(cs); + y = cairo_image_surface_get_height(cs); + if (m->best == NULL) + goto writeMatch; + + if (x < m->targetX && y < m->targetY) + if (m->foundLarger) + // always prefer larger ones + return; + if (x >= m->targetX && y >= m->targetY && !m->foundLarger) + // we set foundLarger below + goto writeMatch; + + x2 = abs(m->targetX - x); + y2 = abs(m->targetY - y); + if (x2 < m->distX && y2 < m->distY) + goto writeMatch; + + // TODO weight one dimension? threshhold? + return; + +writeMatch: + // must set this here too; otherwise the first image will never have ths set + if (x >= m->targetX && y >= m->targetY && !m->foundLarger) + m->foundLarger = TRUE; + m->best = cs; + m->distX = abs(m->targetX - x); + m->distY = abs(m->targetY - y); +} + +cairo_surface_t *uiprivImageAppropriateSurface(uiImage *i, GtkWidget *w) +{ + struct matcher m; + + m.best = NULL; + m.distX = G_MAXINT; + m.distY = G_MAXINT; + m.targetX = i->width * gtk_widget_get_scale_factor(w); + m.targetY = i->height * gtk_widget_get_scale_factor(w); + m.foundLarger = FALSE; + g_ptr_array_foreach(i->images, match, &m); + return m.best; +} diff --git a/dep/libui/unix/label.c b/dep/libui/unix/label.c new file mode 100644 index 0000000..b39fc7c --- /dev/null +++ b/dep/libui/unix/label.c @@ -0,0 +1,36 @@ +// 11 june 2015 +#include "uipriv_unix.h" + +struct uiLabel { + uiUnixControl c; + GtkWidget *widget; + GtkMisc *misc; + GtkLabel *label; +}; + +uiUnixControlAllDefaults(uiLabel) + +char *uiLabelText(uiLabel *l) +{ + return uiUnixStrdupText(gtk_label_get_text(l->label)); +} + +void uiLabelSetText(uiLabel *l, const char *text) +{ + gtk_label_set_text(l->label, text); +} + +uiLabel *uiNewLabel(const char *text) +{ + uiLabel *l; + + uiUnixNewControl(uiLabel, l); + + l->widget = gtk_label_new(text); + l->misc = GTK_MISC(l->widget); + l->label = GTK_LABEL(l->widget); + + gtk_misc_set_alignment(l->misc, 0, 0); + + return l; +} diff --git a/dep/libui/unix/main.c b/dep/libui/unix/main.c new file mode 100644 index 0000000..5d349d3 --- /dev/null +++ b/dep/libui/unix/main.c @@ -0,0 +1,148 @@ +// 6 april 2015 +#include "uipriv_unix.h" + +uiInitOptions uiprivOptions; + +static GHashTable *timers; + +const char *uiInit(uiInitOptions *o) +{ + GError *err = NULL; + const char *msg; + + uiprivOptions = *o; + if (gtk_init_with_args(NULL, NULL, NULL, NULL, NULL, &err) == FALSE) { + msg = g_strdup(err->message); + g_error_free(err); + return msg; + } + uiprivInitAlloc(); + uiprivLoadFutures(); + timers = g_hash_table_new(g_direct_hash, g_direct_equal); + return NULL; +} + +struct timer; // TODO get rid of forward declaration + +static void uninitTimer(gpointer key, gpointer value, gpointer data) +{ + uiprivFree((struct timer *) key); +} + +void uiUninit(void) +{ + g_hash_table_foreach(timers, uninitTimer, NULL); + g_hash_table_destroy(timers); + uiprivUninitMenus(); + uiprivUninitAlloc(); +} + +void uiFreeInitError(const char *err) +{ + g_free((gpointer) err); +} + +static gboolean (*iteration)(gboolean) = NULL; + +void uiMain(void) +{ + iteration = gtk_main_iteration_do; + gtk_main(); +} + +static gboolean stepsQuit = FALSE; + +// the only difference is we ignore the return value from gtk_main_iteration_do(), since it will always be TRUE if gtk_main() was never called +// gtk_main_iteration_do() will still run the main loop regardless +static gboolean stepsIteration(gboolean block) +{ + gtk_main_iteration_do(block); + return stepsQuit; +} + +void uiMainSteps(void) +{ + iteration = stepsIteration; +} + +int uiMainStep(int wait) +{ + gboolean block; + + block = FALSE; + if (wait) + block = TRUE; + return (*iteration)(block) == FALSE; +} + +// gtk_main_quit() may run immediately, or it may wait for other pending events; "it depends" (thanks mclasen in irc.gimp.net/#gtk+) +// PostQuitMessage() on Windows always waits, so we must do so too +// we'll do it by using an idle callback +static gboolean quit(gpointer data) +{ + if (iteration == stepsIteration) + stepsQuit = TRUE; + // TODO run a gtk_main() here just to do the cleanup steps of syncing the clipboard and other stuff gtk_main() does before it returns + else + gtk_main_quit(); + return FALSE; +} + +void uiQuit(void) +{ + gdk_threads_add_idle(quit, NULL); +} + +struct queued { + void (*f)(void *); + void *data; +}; + +static gboolean doqueued(gpointer data) +{ + struct queued *q = (struct queued *) data; + + (*(q->f))(q->data); + g_free(q); + return FALSE; +} + +void uiQueueMain(void (*f)(void *data), void *data) +{ + struct queued *q; + + // we have to use g_new0()/g_free() because uiprivAlloc() is only safe to call on the main thread + // for some reason it didn't affect me, but it did affect krakjoe + q = g_new0(struct queued, 1); + q->f = f; + q->data = data; + gdk_threads_add_idle(doqueued, q); +} + +struct timer { + int (*f)(void *); + void *data; +}; + +static gboolean doTimer(gpointer data) +{ + struct timer *t = (struct timer *) data; + + if (!(*(t->f))(t->data)) { + g_hash_table_remove(timers, t); + uiprivFree(t); + return FALSE; + } + return TRUE; +} + +void uiTimer(int milliseconds, int (*f)(void *data), void *data) +{ + struct timer *t; + + t = uiprivNew(struct timer); + t->f = f; + t->data = data; + g_timeout_add(milliseconds, doTimer, t); + g_hash_table_add(timers, t); +} diff --git a/dep/libui/unix/menu.c b/dep/libui/unix/menu.c new file mode 100644 index 0000000..a3142ee --- /dev/null +++ b/dep/libui/unix/menu.c @@ -0,0 +1,366 @@ +// 23 april 2015 +#include "uipriv_unix.h" + +static GArray *menus = NULL; +static gboolean menusFinalized = FALSE; +static gboolean hasQuit = FALSE; +static gboolean hasPreferences = FALSE; +static gboolean hasAbout = FALSE; + +struct uiMenu { + char *name; + GArray *items; // []*uiMenuItem +}; + +struct uiMenuItem { + char *name; + int type; + void (*onClicked)(uiMenuItem *, uiWindow *, void *); + void *onClickedData; + GType gtype; // template for new instances; kept in sync with everything else + gboolean disabled; + gboolean checked; + GHashTable *windows; // map[GtkMenuItem]*menuItemWindow +}; + +struct menuItemWindow { + uiWindow *w; + gulong signal; +}; + +enum { + typeRegular, + typeCheckbox, + typeQuit, + typePreferences, + typeAbout, + typeSeparator, +}; + +// we do NOT want programmatic updates to raise an ::activated signal +static void singleSetChecked(GtkCheckMenuItem *menuitem, gboolean checked, gulong signal) +{ + g_signal_handler_block(menuitem, signal); + gtk_check_menu_item_set_active(menuitem, checked); + g_signal_handler_unblock(menuitem, signal); +} + +static void setChecked(uiMenuItem *item, gboolean checked) +{ + GHashTableIter iter; + gpointer widget; + gpointer ww; + struct menuItemWindow *w; + + item->checked = checked; + g_hash_table_iter_init(&iter, item->windows); + while (g_hash_table_iter_next(&iter, &widget, &ww)) { + w = (struct menuItemWindow *) ww; + singleSetChecked(GTK_CHECK_MENU_ITEM(widget), item->checked, w->signal); + } +} + +static void onClicked(GtkMenuItem *menuitem, gpointer data) +{ + uiMenuItem *item = uiMenuItem(data); + struct menuItemWindow *w; + + // we need to manually update the checked states of all menu items if one changes + // notice that this is getting the checked state of the menu item that this signal is sent from + if (item->type == typeCheckbox) + setChecked(item, gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menuitem))); + + w = (struct menuItemWindow *) g_hash_table_lookup(item->windows, menuitem); + (*(item->onClicked))(item, w->w, item->onClickedData); +} + +static void defaultOnClicked(uiMenuItem *item, uiWindow *w, void *data) +{ + // do nothing +} + +static void onQuitClicked(uiMenuItem *item, uiWindow *w, void *data) +{ + if (uiprivShouldQuit()) + uiQuit(); +} + +static void menuItemEnableDisable(uiMenuItem *item, gboolean enabled) +{ + GHashTableIter iter; + gpointer widget; + + item->disabled = !enabled; + g_hash_table_iter_init(&iter, item->windows); + while (g_hash_table_iter_next(&iter, &widget, NULL)) + gtk_widget_set_sensitive(GTK_WIDGET(widget), enabled); +} + +void uiMenuItemEnable(uiMenuItem *item) +{ + menuItemEnableDisable(item, TRUE); +} + +void uiMenuItemDisable(uiMenuItem *item) +{ + menuItemEnableDisable(item, FALSE); +} + +void uiMenuItemOnClicked(uiMenuItem *item, void (*f)(uiMenuItem *, uiWindow *, void *), void *data) +{ + if (item->type == typeQuit) + uiprivUserBug("You cannot call uiMenuItemOnClicked() on a Quit item; use uiOnShouldQuit() instead."); + item->onClicked = f; + item->onClickedData = data; +} + +int uiMenuItemChecked(uiMenuItem *item) +{ + return item->checked != FALSE; +} + +void uiMenuItemSetChecked(uiMenuItem *item, int checked) +{ + gboolean c; + + // use explicit values + c = FALSE; + if (checked) + c = TRUE; + setChecked(item, c); +} + +static uiMenuItem *newItem(uiMenu *m, int type, const char *name) +{ + uiMenuItem *item; + + if (menusFinalized) + uiprivUserBug("You cannot create a new menu item after menus have been finalized."); + + item = uiprivNew(uiMenuItem); + + g_array_append_val(m->items, item); + + item->type = type; + switch (item->type) { + case typeQuit: + item->name = g_strdup("Quit"); + break; + case typePreferences: + item->name = g_strdup("Preferences..."); + break; + case typeAbout: + item->name = g_strdup("About"); + break; + case typeSeparator: + break; + default: + item->name = g_strdup(name); + break; + } + + if (item->type == typeQuit) { + // can't call uiMenuItemOnClicked() here + item->onClicked = onQuitClicked; + item->onClickedData = NULL; + } else + uiMenuItemOnClicked(item, defaultOnClicked, NULL); + + switch (item->type) { + case typeCheckbox: + item->gtype = GTK_TYPE_CHECK_MENU_ITEM; + break; + case typeSeparator: + item->gtype = GTK_TYPE_SEPARATOR_MENU_ITEM; + break; + default: + item->gtype = GTK_TYPE_MENU_ITEM; + break; + } + + item->windows = g_hash_table_new(g_direct_hash, g_direct_equal); + + return item; +} + +uiMenuItem *uiMenuAppendItem(uiMenu *m, const char *name) +{ + return newItem(m, typeRegular, name); +} + +uiMenuItem *uiMenuAppendCheckItem(uiMenu *m, const char *name) +{ + return newItem(m, typeCheckbox, name); +} + +uiMenuItem *uiMenuAppendQuitItem(uiMenu *m) +{ + if (hasQuit) + uiprivUserBug("You cannot have multiple Quit menu items in the same program."); + hasQuit = TRUE; + newItem(m, typeSeparator, NULL); + return newItem(m, typeQuit, NULL); +} + +uiMenuItem *uiMenuAppendPreferencesItem(uiMenu *m) +{ + if (hasPreferences) + uiprivUserBug("You cannot have multiple Preferences menu items in the same program."); + hasPreferences = TRUE; + newItem(m, typeSeparator, NULL); + return newItem(m, typePreferences, NULL); +} + +uiMenuItem *uiMenuAppendAboutItem(uiMenu *m) +{ + if (hasAbout) + uiprivUserBug("You cannot have multiple About menu items in the same program."); + hasAbout = TRUE; + newItem(m, typeSeparator, NULL); + return newItem(m, typeAbout, NULL); +} + +void uiMenuAppendSeparator(uiMenu *m) +{ + newItem(m, typeSeparator, NULL); +} + +uiMenu *uiNewMenu(const char *name) +{ + uiMenu *m; + + if (menusFinalized) + uiprivUserBug("You cannot create a new menu after menus have been finalized."); + if (menus == NULL) + menus = g_array_new(FALSE, TRUE, sizeof (uiMenu *)); + + m = uiprivNew(uiMenu); + + g_array_append_val(menus, m); + + m->name = g_strdup(name); + m->items = g_array_new(FALSE, TRUE, sizeof (uiMenuItem *)); + + return m; +} + +static void appendMenuItem(GtkMenuShell *submenu, uiMenuItem *item, uiWindow *w) +{ + GtkWidget *menuitem; + gulong signal; + struct menuItemWindow *ww; + + menuitem = g_object_new(item->gtype, NULL); + if (item->name != NULL) + gtk_menu_item_set_label(GTK_MENU_ITEM(menuitem), item->name); + if (item->type != typeSeparator) { + signal = g_signal_connect(menuitem, "activate", G_CALLBACK(onClicked), item); + gtk_widget_set_sensitive(menuitem, !item->disabled); + if (item->type == typeCheckbox) + singleSetChecked(GTK_CHECK_MENU_ITEM(menuitem), item->checked, signal); + } + gtk_menu_shell_append(submenu, menuitem); + ww = uiprivNew(struct menuItemWindow); + ww->w = w; + ww->signal = signal; + g_hash_table_insert(item->windows, menuitem, ww); +} + +GtkWidget *uiprivMakeMenubar(uiWindow *w) +{ + GtkWidget *menubar; + guint i, j; + uiMenu *m; + GtkWidget *menuitem; + GtkWidget *submenu; + + menusFinalized = TRUE; + + menubar = gtk_menu_bar_new(); + + if (menus != NULL) + for (i = 0; i < menus->len; i++) { + m = g_array_index(menus, uiMenu *, i); + menuitem = gtk_menu_item_new_with_label(m->name); + submenu = gtk_menu_new(); + gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), submenu); + for (j = 0; j < m->items->len; j++) + appendMenuItem(GTK_MENU_SHELL(submenu), g_array_index(m->items, uiMenuItem *, j), w); + gtk_menu_shell_append(GTK_MENU_SHELL(menubar), menuitem); + } + + gtk_widget_set_hexpand(menubar, TRUE); + gtk_widget_set_halign(menubar, GTK_ALIGN_FILL); + return menubar; +} + +struct freeMenuItemData { + GArray *items; + guint i; +}; + +static void freeMenuItem(GtkWidget *widget, gpointer data) +{ + struct freeMenuItemData *fmi = (struct freeMenuItemData *) data; + uiMenuItem *item; + struct menuItemWindow *w; + + item = g_array_index(fmi->items, uiMenuItem *, fmi->i); + w = (struct menuItemWindow *) g_hash_table_lookup(item->windows, widget); + if (g_hash_table_remove(item->windows, widget) == FALSE) + uiprivImplBug("GtkMenuItem %p not in menu item's item/window map", widget); + uiprivFree(w); + fmi->i++; +} + +static void freeMenu(GtkWidget *widget, gpointer data) +{ + guint *i = (guint *) data; + uiMenu *m; + GtkMenuItem *item; + GtkWidget *submenu; + struct freeMenuItemData fmi; + + m = g_array_index(menus, uiMenu *, *i); + item = GTK_MENU_ITEM(widget); + submenu = gtk_menu_item_get_submenu(item); + fmi.items = m->items; + fmi.i = 0; + gtk_container_foreach(GTK_CONTAINER(submenu), freeMenuItem, &fmi); + (*i)++; +} + +void uiprivFreeMenubar(GtkWidget *mb) +{ + guint i; + + i = 0; + gtk_container_foreach(GTK_CONTAINER(mb), freeMenu, &i); + // no need to worry about destroying any widgets; destruction of the window they're in will do it for us +} + +void uiprivUninitMenus(void) +{ + uiMenu *m; + uiMenuItem *item; + guint i, j; + + if (menus == NULL) + return; + for (i = 0; i < menus->len; i++) { + m = g_array_index(menus, uiMenu *, i); + g_free(m->name); + for (j = 0; j < m->items->len; j++) { + item = g_array_index(m->items, uiMenuItem *, j); + if (g_hash_table_size(item->windows) != 0) + // TODO is this really a uiprivUserBug()? + uiprivImplBug("menu item %p (%s) still has uiWindows attached; did you forget to destroy some windows?", item, item->name); + g_free(item->name); + g_hash_table_destroy(item->windows); + uiprivFree(item); + } + g_array_free(m->items, TRUE); + uiprivFree(m); + } + g_array_free(menus, TRUE); +} diff --git a/dep/libui/unix/meson.build b/dep/libui/unix/meson.build new file mode 100644 index 0000000..f8004fb --- /dev/null +++ b/dep/libui/unix/meson.build @@ -0,0 +1,62 @@ +# 23 march 2019 + +libui_sources += [ + 'unix/alloc.c', + 'unix/area.c', + 'unix/attrstr.c', + 'unix/box.c', + 'unix/button.c', + 'unix/cellrendererbutton.c', + 'unix/checkbox.c', + 'unix/child.c', + 'unix/colorbutton.c', + 'unix/combobox.c', + 'unix/control.c', + 'unix/datetimepicker.c', + 'unix/debug.c', + 'unix/draw.c', + 'unix/drawmatrix.c', + 'unix/drawpath.c', + 'unix/drawtext.c', + 'unix/editablecombo.c', + 'unix/entry.c', + 'unix/fontbutton.c', + 'unix/fontmatch.c', + 'unix/form.c', + 'unix/future.c', + 'unix/graphemes.c', + 'unix/grid.c', + 'unix/group.c', + 'unix/image.c', + 'unix/label.c', + 'unix/main.c', + 'unix/menu.c', + 'unix/multilineentry.c', + 'unix/opentype.c', + 'unix/progressbar.c', + 'unix/radiobuttons.c', + 'unix/separator.c', + 'unix/slider.c', + 'unix/spinbox.c', + 'unix/stddialogs.c', + 'unix/tab.c', + 'unix/table.c', + 'unix/tablemodel.c', + 'unix/text.c', + 'unix/util.c', + 'unix/window.c', +] + +libui_deps += [ + dependency('gtk+-3.0', + version: '>=3.10.0', + method: 'pkg-config', + required: true), + # We specify these as not required because some Unix systems include them with libc instead of providing them as separate files (thanks textshell and jpakkane in freenode #mesonbuild) + meson.get_compiler('c').find_library('m', + required: false), + meson.get_compiler('c').find_library('dl', + required: false), +] +libui_soversion = '0' +libui_rpath = '$ORIGIN' diff --git a/dep/libui/unix/multilineentry.c b/dep/libui/unix/multilineentry.c new file mode 100644 index 0000000..228dc80 --- /dev/null +++ b/dep/libui/unix/multilineentry.c @@ -0,0 +1,126 @@ +// 6 december 2015 +#include "uipriv_unix.h" + +// TODO GTK_WRAP_WORD_CHAR to avoid spurious resizes? + +struct uiMultilineEntry { + uiUnixControl c; + GtkWidget *widget; + GtkContainer *scontainer; + GtkScrolledWindow *sw; + GtkWidget *textviewWidget; + GtkTextView *textview; + GtkTextBuffer *textbuf; + void (*onChanged)(uiMultilineEntry *, void *); + void *onChangedData; + gulong onChangedSignal; +}; + +uiUnixControlAllDefaults(uiMultilineEntry) + +static void onChanged(GtkTextBuffer *textbuf, gpointer data) +{ + uiMultilineEntry *e = uiMultilineEntry(data); + + (*(e->onChanged))(e, e->onChangedData); +} + +static void defaultOnChanged(uiMultilineEntry *e, void *data) +{ + // do nothing +} + +char *uiMultilineEntryText(uiMultilineEntry *e) +{ + GtkTextIter start, end; + char *tret, *out; + + gtk_text_buffer_get_start_iter(e->textbuf, &start); + gtk_text_buffer_get_end_iter(e->textbuf, &end); + tret = gtk_text_buffer_get_text(e->textbuf, &start, &end, TRUE); + // theoretically we could just return tret because uiUnixStrdupText() is just g_strdup(), but if that ever changes we can't, so let's do it this way to be safe + out = uiUnixStrdupText(tret); + g_free(tret); + return out; +} + +void uiMultilineEntrySetText(uiMultilineEntry *e, const char *text) +{ + // we need to inhibit sending of ::changed because this WILL send a ::changed otherwise + g_signal_handler_block(e->textbuf, e->onChangedSignal); + gtk_text_buffer_set_text(e->textbuf, text, -1); + g_signal_handler_unblock(e->textbuf, e->onChangedSignal); +} + +// TODO scroll to end? +void uiMultilineEntryAppend(uiMultilineEntry *e, const char *text) +{ + GtkTextIter end; + + gtk_text_buffer_get_end_iter(e->textbuf, &end); + // we need to inhibit sending of ::changed because this WILL send a ::changed otherwise + g_signal_handler_block(e->textbuf, e->onChangedSignal); + gtk_text_buffer_insert(e->textbuf, &end, text, -1); + g_signal_handler_unblock(e->textbuf, e->onChangedSignal); +} + +void uiMultilineEntryOnChanged(uiMultilineEntry *e, void (*f)(uiMultilineEntry *e, void *data), void *data) +{ + e->onChanged = f; + e->onChangedData = data; +} + +int uiMultilineEntryReadOnly(uiMultilineEntry *e) +{ + return gtk_text_view_get_editable(e->textview) == FALSE; +} + +void uiMultilineEntrySetReadOnly(uiMultilineEntry *e, int readonly) +{ + gboolean editable; + + editable = TRUE; + if (readonly) + editable = FALSE; + gtk_text_view_set_editable(e->textview, editable); +} + +static uiMultilineEntry *finishMultilineEntry(GtkPolicyType hpolicy, GtkWrapMode wrapMode) +{ + uiMultilineEntry *e; + + uiUnixNewControl(uiMultilineEntry, e); + + e->widget = gtk_scrolled_window_new(NULL, NULL); + e->scontainer = GTK_CONTAINER(e->widget); + e->sw = GTK_SCROLLED_WINDOW(e->widget); + gtk_scrolled_window_set_policy(e->sw, + hpolicy, + GTK_POLICY_AUTOMATIC); + gtk_scrolled_window_set_shadow_type(e->sw, GTK_SHADOW_IN); + + e->textviewWidget = gtk_text_view_new(); + e->textview = GTK_TEXT_VIEW(e->textviewWidget); + gtk_text_view_set_wrap_mode(e->textview, wrapMode); + + gtk_container_add(e->scontainer, e->textviewWidget); + // and make the text view visible; only the scrolled window's visibility is controlled by libui + gtk_widget_show(e->textviewWidget); + + e->textbuf = gtk_text_view_get_buffer(e->textview); + + e->onChangedSignal = g_signal_connect(e->textbuf, "changed", G_CALLBACK(onChanged), e); + uiMultilineEntryOnChanged(e, defaultOnChanged, NULL); + + return e; +} + +uiMultilineEntry *uiNewMultilineEntry(void) +{ + return finishMultilineEntry(GTK_POLICY_NEVER, GTK_WRAP_WORD); +} + +uiMultilineEntry *uiNewNonWrappingMultilineEntry(void) +{ + return finishMultilineEntry(GTK_POLICY_AUTOMATIC, GTK_WRAP_NONE); +} diff --git a/dep/libui/unix/opentype.c b/dep/libui/unix/opentype.c new file mode 100644 index 0000000..281acda --- /dev/null +++ b/dep/libui/unix/opentype.c @@ -0,0 +1,26 @@ +// 11 may 2017 +#include "uipriv_unix.h" +#include "attrstr.h" + +// see https://developer.mozilla.org/en/docs/Web/CSS/font-feature-settings +static uiForEach toCSS(const uiOpenTypeFeatures *otf, char a, char b, char c, char d, uint32_t value, void *data) +{ + GString *s = (GString *) data; + + // the last trailing comma is removed after foreach is done + g_string_append_printf(s, "\"%c%c%c%c\" %" PRIu32 ", ", + a, b, c, d, value); + return uiForEachContinue; +} + +GString *uiprivOpenTypeFeaturesToPangoCSSFeaturesString(const uiOpenTypeFeatures *otf) +{ + GString *s; + + s = g_string_new(""); + uiOpenTypeFeaturesForEach(otf, toCSS, s); + if (s->len != 0) + // and remove the last comma + g_string_truncate(s, s->len - 2); + return s; +} diff --git a/dep/libui/unix/progressbar.c b/dep/libui/unix/progressbar.c new file mode 100644 index 0000000..46f0e10 --- /dev/null +++ b/dep/libui/unix/progressbar.c @@ -0,0 +1,74 @@ +// 11 june 2015 +#include "uipriv_unix.h" + +// LONGTERM: +// - in GTK+ 3.22 at least, running both a GtkProgressBar and a GtkCellRendererProgress in pulse mode with our code will cause the former to slow down and eventually stop, and I can't tell why at all + +struct uiProgressBar { + uiUnixControl c; + GtkWidget *widget; + GtkProgressBar *pbar; + gboolean indeterminate; + guint pulser; +}; + +uiUnixControlAllDefaultsExceptDestroy(uiProgressBar) + +static void uiProgressBarDestroy(uiControl *c) +{ + uiProgressBar *p = uiProgressBar(c); + + // be sure to stop the timeout now + if (p->indeterminate) + g_source_remove(p->pulser); + g_object_unref(p->widget); + uiFreeControl(uiControl(p)); +} + +int uiProgressBarValue(uiProgressBar *p) +{ + if (p->indeterminate) + return -1; + return (int) (gtk_progress_bar_get_fraction(p->pbar) * 100); +} + +static gboolean pulse(void* data) +{ + uiProgressBar *p = uiProgressBar(data); + + gtk_progress_bar_pulse(p->pbar); + return TRUE; +} + +void uiProgressBarSetValue(uiProgressBar *p, int value) +{ + if (value == -1) { + if (!p->indeterminate) { + p->indeterminate = TRUE; + // TODO verify the timeout + p->pulser = g_timeout_add(100, pulse, p); + } + return; + } + if (p->indeterminate) { + p->indeterminate = FALSE; + g_source_remove(p->pulser); + } + + if (value < 0 || value > 100) + uiprivUserBug("Value %d is out of range for a uiProgressBar.", value); + + gtk_progress_bar_set_fraction(p->pbar, ((gdouble) value) / 100); +} + +uiProgressBar *uiNewProgressBar(void) +{ + uiProgressBar *p; + + uiUnixNewControl(uiProgressBar, p); + + p->widget = gtk_progress_bar_new(); + p->pbar = GTK_PROGRESS_BAR(p->widget); + + return p; +} diff --git a/dep/libui/unix/radiobuttons.c b/dep/libui/unix/radiobuttons.c new file mode 100644 index 0000000..da41107 --- /dev/null +++ b/dep/libui/unix/radiobuttons.c @@ -0,0 +1,121 @@ +// 11 june 2015 +#include "uipriv_unix.h" + +// on GTK+ a uiRadioButtons is a GtkBox with each of the GtkRadioButtons as children + +struct uiRadioButtons { + uiUnixControl c; + GtkWidget *widget; + GtkContainer *container; + GtkBox *box; + GPtrArray *buttons; + void (*onSelected)(uiRadioButtons *, void *); + void *onSelectedData; + gboolean changing; +}; + +uiUnixControlAllDefaultsExceptDestroy(uiRadioButtons) + +static void defaultOnSelected(uiRadioButtons *r, void *data) +{ + // do nothing +} + +static void onToggled(GtkToggleButton *tb, gpointer data) +{ + uiRadioButtons *r = uiRadioButtons(data); + + // only care if a button is selected + if (!gtk_toggle_button_get_active(tb)) + return; + // ignore programmatic changes + if (r->changing) + return; + (*(r->onSelected))(r, r->onSelectedData); +} + +static void uiRadioButtonsDestroy(uiControl *c) +{ + uiRadioButtons *r = uiRadioButtons(c); + GtkWidget *b; + + while (r->buttons->len != 0) { + b = GTK_WIDGET(g_ptr_array_remove_index(r->buttons, 0)); + gtk_widget_destroy(b); + } + g_ptr_array_free(r->buttons, TRUE); + // and free ourselves + g_object_unref(r->widget); + uiFreeControl(uiControl(r)); +} + +void uiRadioButtonsAppend(uiRadioButtons *r, const char *text) +{ + GtkWidget *rb; + GtkRadioButton *previous; + + previous = NULL; + if (r->buttons->len > 0) + previous = GTK_RADIO_BUTTON(g_ptr_array_index(r->buttons, 0)); + rb = gtk_radio_button_new_with_label_from_widget(previous, text); + g_signal_connect(rb, "toggled", G_CALLBACK(onToggled), r); + gtk_container_add(r->container, rb); + g_ptr_array_add(r->buttons, rb); + gtk_widget_show(rb); +} + +int uiRadioButtonsSelected(uiRadioButtons *r) +{ + GtkToggleButton *tb; + guint i; + + for (i = 0; i < r->buttons->len; i++) { + tb = GTK_TOGGLE_BUTTON(g_ptr_array_index(r->buttons, i)); + if (gtk_toggle_button_get_active(tb)) + return i; + } + return -1; +} + +void uiRadioButtonsSetSelected(uiRadioButtons *r, int n) +{ + GtkToggleButton *tb; + gboolean active; + + active = TRUE; + // TODO this doesn't work + if (n == -1) { + n = uiRadioButtonsSelected(r); + if (n == -1) // no selection; keep it that way + return; + active = FALSE; + } + tb = GTK_TOGGLE_BUTTON(g_ptr_array_index(r->buttons, n)); + // this is easier than remembering all the signals + r->changing = TRUE; + gtk_toggle_button_set_active(tb, active); + r->changing = FALSE; +} + +void uiRadioButtonsOnSelected(uiRadioButtons *r, void (*f)(uiRadioButtons *, void *), void *data) +{ + r->onSelected = f; + r->onSelectedData = data; +} + +uiRadioButtons *uiNewRadioButtons(void) +{ + uiRadioButtons *r; + + uiUnixNewControl(uiRadioButtons, r); + + r->widget = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); + r->container = GTK_CONTAINER(r->widget); + r->box = GTK_BOX(r->widget); + + r->buttons = g_ptr_array_new(); + + uiRadioButtonsOnSelected(r, defaultOnSelected, NULL); + + return r; +} diff --git a/dep/libui/unix/separator.c b/dep/libui/unix/separator.c new file mode 100644 index 0000000..02c75da --- /dev/null +++ b/dep/libui/unix/separator.c @@ -0,0 +1,34 @@ +// 11 june 2015 +#include "uipriv_unix.h" + +struct uiSeparator { + uiUnixControl c; + GtkWidget *widget; + GtkSeparator *separator; +}; + +uiUnixControlAllDefaults(uiSeparator) + +uiSeparator *uiNewHorizontalSeparator(void) +{ + uiSeparator *s; + + uiUnixNewControl(uiSeparator, s); + + s->widget = gtk_separator_new(GTK_ORIENTATION_HORIZONTAL); + s->separator = GTK_SEPARATOR(s->widget); + + return s; +} + +uiSeparator *uiNewVerticalSeparator(void) +{ + uiSeparator *s; + + uiUnixNewControl(uiSeparator, s); + + s->widget = gtk_separator_new(GTK_ORIENTATION_VERTICAL); + s->separator = GTK_SEPARATOR(s->widget); + + return s; +} diff --git a/dep/libui/unix/slider.c b/dep/libui/unix/slider.c new file mode 100644 index 0000000..7f0cc24 --- /dev/null +++ b/dep/libui/unix/slider.c @@ -0,0 +1,71 @@ +// 11 june 2015 +#include "uipriv_unix.h" + +struct uiSlider { + uiUnixControl c; + GtkWidget *widget; + GtkRange *range; + GtkScale *scale; + void (*onChanged)(uiSlider *, void *); + void *onChangedData; + gulong onChangedSignal; +}; + +uiUnixControlAllDefaults(uiSlider) + +static void onChanged(GtkRange *range, gpointer data) +{ + uiSlider *s = uiSlider(data); + + (*(s->onChanged))(s, s->onChangedData); +} + +static void defaultOnChanged(uiSlider *s, void *data) +{ + // do nothing +} + +int uiSliderValue(uiSlider *s) +{ + return gtk_range_get_value(s->range); +} + +void uiSliderSetValue(uiSlider *s, int value) +{ + // we need to inhibit sending of ::value-changed because this WILL send a ::value-changed otherwise + g_signal_handler_block(s->range, s->onChangedSignal); + gtk_range_set_value(s->range, value); + g_signal_handler_unblock(s->range, s->onChangedSignal); +} + +void uiSliderOnChanged(uiSlider *s, void (*f)(uiSlider *, void *), void *data) +{ + s->onChanged = f; + s->onChangedData = data; +} + +uiSlider *uiNewSlider(int min, int max) +{ + uiSlider *s; + int temp; + + if (min >= max) { + temp = min; + min = max; + max = temp; + } + + uiUnixNewControl(uiSlider, s); + + s->widget = gtk_scale_new_with_range(GTK_ORIENTATION_HORIZONTAL, min, max, 1); + s->range = GTK_RANGE(s->widget); + s->scale = GTK_SCALE(s->widget); + + // ensure integers, just to be safe + gtk_scale_set_digits(s->scale, 0); + + s->onChangedSignal = g_signal_connect(s->scale, "value-changed", G_CALLBACK(onChanged), s); + uiSliderOnChanged(s, defaultOnChanged, NULL); + + return s; +} diff --git a/dep/libui/unix/spinbox.c b/dep/libui/unix/spinbox.c new file mode 100644 index 0000000..90a5d3c --- /dev/null +++ b/dep/libui/unix/spinbox.c @@ -0,0 +1,72 @@ +// 11 june 2015 +#include "uipriv_unix.h" + +struct uiSpinbox { + uiUnixControl c; + GtkWidget *widget; + GtkEntry *entry; + GtkSpinButton *spinButton; + void (*onChanged)(uiSpinbox *, void *); + void *onChangedData; + gulong onChangedSignal; +}; + +uiUnixControlAllDefaults(uiSpinbox) + +static void onChanged(GtkSpinButton *sb, gpointer data) +{ + uiSpinbox *s = uiSpinbox(data); + + (*(s->onChanged))(s, s->onChangedData); +} + +static void defaultOnChanged(uiSpinbox *s, void *data) +{ + // do nothing +} + +int uiSpinboxValue(uiSpinbox *s) +{ + return gtk_spin_button_get_value(s->spinButton); +} + +void uiSpinboxSetValue(uiSpinbox *s, int value) +{ + // we need to inhibit sending of ::value-changed because this WILL send a ::value-changed otherwise + g_signal_handler_block(s->spinButton, s->onChangedSignal); + // this clamps for us + gtk_spin_button_set_value(s->spinButton, (gdouble) value); + g_signal_handler_unblock(s->spinButton, s->onChangedSignal); +} + +void uiSpinboxOnChanged(uiSpinbox *s, void (*f)(uiSpinbox *, void *), void *data) +{ + s->onChanged = f; + s->onChangedData = data; +} + +uiSpinbox *uiNewSpinbox(int min, int max) +{ + uiSpinbox *s; + int temp; + + if (min >= max) { + temp = min; + min = max; + max = temp; + } + + uiUnixNewControl(uiSpinbox, s); + + s->widget = gtk_spin_button_new_with_range(min, max, 1); + s->entry = GTK_ENTRY(s->widget); + s->spinButton = GTK_SPIN_BUTTON(s->widget); + + // ensure integers, just to be safe + gtk_spin_button_set_digits(s->spinButton, 0); + + s->onChangedSignal = g_signal_connect(s->spinButton, "value-changed", G_CALLBACK(onChanged), s); + uiSpinboxOnChanged(s, defaultOnChanged, NULL); + + return s; +} diff --git a/dep/libui/unix/stddialogs.c b/dep/libui/unix/stddialogs.c new file mode 100644 index 0000000..93302f7 --- /dev/null +++ b/dep/libui/unix/stddialogs.c @@ -0,0 +1,66 @@ +// 26 june 2015 +#include "uipriv_unix.h" + +// LONGTERM figure out why, and describe, that this is the desired behavior +// LONGTERM also point out that font and color buttons also work like this + +#define windowWindow(w) (GTK_WINDOW(uiControlHandle(uiControl(w)))) + +static char *filedialog(GtkWindow *parent, GtkFileChooserAction mode, const gchar *confirm) +{ + GtkWidget *fcd; + GtkFileChooser *fc; + gint response; + char *filename; + + fcd = gtk_file_chooser_dialog_new(NULL, parent, mode, + "_Cancel", GTK_RESPONSE_CANCEL, + confirm, GTK_RESPONSE_ACCEPT, + NULL); + fc = GTK_FILE_CHOOSER(fcd); + gtk_file_chooser_set_local_only(fc, FALSE); + gtk_file_chooser_set_select_multiple(fc, FALSE); + gtk_file_chooser_set_show_hidden(fc, TRUE); + gtk_file_chooser_set_do_overwrite_confirmation(fc, TRUE); + gtk_file_chooser_set_create_folders(fc, TRUE); + response = gtk_dialog_run(GTK_DIALOG(fcd)); + if (response != GTK_RESPONSE_ACCEPT) { + gtk_widget_destroy(fcd); + return NULL; + } + filename = uiUnixStrdupText(gtk_file_chooser_get_filename(fc)); + gtk_widget_destroy(fcd); + return filename; +} + +char *uiOpenFile(uiWindow *parent) +{ + return filedialog(windowWindow(parent), GTK_FILE_CHOOSER_ACTION_OPEN, "_Open"); +} + +char *uiSaveFile(uiWindow *parent) +{ + return filedialog(windowWindow(parent), GTK_FILE_CHOOSER_ACTION_SAVE, "_Save"); +} + +static void msgbox(GtkWindow *parent, const char *title, const char *description, GtkMessageType type, GtkButtonsType buttons) +{ + GtkWidget *md; + + md = gtk_message_dialog_new(parent, GTK_DIALOG_MODAL, + type, buttons, + "%s", title); + gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(md), "%s", description); + gtk_dialog_run(GTK_DIALOG(md)); + gtk_widget_destroy(md); +} + +void uiMsgBox(uiWindow *parent, const char *title, const char *description) +{ + msgbox(windowWindow(parent), title, description, GTK_MESSAGE_OTHER, GTK_BUTTONS_OK); +} + +void uiMsgBoxError(uiWindow *parent, const char *title, const char *description) +{ + msgbox(windowWindow(parent), title, description, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK); +} diff --git a/dep/libui/unix/tab.c b/dep/libui/unix/tab.c new file mode 100644 index 0000000..b49c98b --- /dev/null +++ b/dep/libui/unix/tab.c @@ -0,0 +1,97 @@ +// 11 june 2015 +#include "uipriv_unix.h" + +struct uiTab { + uiUnixControl c; + + GtkWidget *widget; + GtkContainer *container; + GtkNotebook *notebook; + + GArray *pages; // []*uiprivChild +}; + +uiUnixControlAllDefaultsExceptDestroy(uiTab) + +static void uiTabDestroy(uiControl *c) +{ + uiTab *t = uiTab(c); + guint i; + uiprivChild *page; + + for (i = 0; i < t->pages->len; i++) { + page = g_array_index(t->pages, uiprivChild *, i); + uiprivChildDestroy(page); + } + g_array_free(t->pages, TRUE); + // and free ourselves + g_object_unref(t->widget); + uiFreeControl(uiControl(t)); +} + +void uiTabAppend(uiTab *t, const char *name, uiControl *child) +{ + uiTabInsertAt(t, name, t->pages->len, child); +} + +void uiTabInsertAt(uiTab *t, const char *name, int n, uiControl *child) +{ + uiprivChild *page; + + // this will create a tab, because of gtk_container_add() + page = uiprivNewChildWithBox(child, uiControl(t), t->container, 0); + + gtk_notebook_set_tab_label_text(t->notebook, uiprivChildBox(page), name); + gtk_notebook_reorder_child(t->notebook, uiprivChildBox(page), n); + + g_array_insert_val(t->pages, n, page); +} + +void uiTabDelete(uiTab *t, int n) +{ + uiprivChild *page; + + page = g_array_index(t->pages, uiprivChild *, n); + // this will remove the tab, because gtk_widget_destroy() calls gtk_container_remove() + uiprivChildRemove(page); + g_array_remove_index(t->pages, n); +} + +int uiTabNumPages(uiTab *t) +{ + return t->pages->len; +} + +int uiTabMargined(uiTab *t, int n) +{ + uiprivChild *page; + + page = g_array_index(t->pages, uiprivChild *, n); + return uiprivChildFlag(page); +} + +void uiTabSetMargined(uiTab *t, int n, int margined) +{ + uiprivChild *page; + + page = g_array_index(t->pages, uiprivChild *, n); + uiprivChildSetFlag(page, margined); + uiprivChildSetMargined(page, uiprivChildFlag(page)); +} + +uiTab *uiNewTab(void) +{ + uiTab *t; + + uiUnixNewControl(uiTab, t); + + t->widget = gtk_notebook_new(); + t->container = GTK_CONTAINER(t->widget); + t->notebook = GTK_NOTEBOOK(t->widget); + + gtk_notebook_set_scrollable(t->notebook, TRUE); + + t->pages = g_array_new(FALSE, TRUE, sizeof (uiprivChild *)); + + return t; +} diff --git a/dep/libui/unix/table.c b/dep/libui/unix/table.c new file mode 100644 index 0000000..e29ada0 --- /dev/null +++ b/dep/libui/unix/table.c @@ -0,0 +1,524 @@ +// 26 june 2016 +#include "uipriv_unix.h" +#include "table.h" + +// TODO with GDK_SCALE set to 2 the 32x32 images are scaled up to 64x64? + +struct uiTable { + uiUnixControl c; + GtkWidget *widget; + GtkContainer *scontainer; + GtkScrolledWindow *sw; + GtkWidget *treeWidget; + GtkTreeView *tv; + uiTableModel *model; + GPtrArray *columnParams; + int backgroundColumn; + // keys are struct rowcol, values are gint + // TODO document this properly + GHashTable *indeterminatePositions; + guint indeterminateTimer; +}; + +// use the same size as GtkFileChooserWidget's treeview +// TODO refresh when icon theme changes +// TODO doesn't work when scaled? +// TODO is this even necessary? +static void setImageSize(GtkCellRenderer *r) +{ + gint size; + gint width, height; + gint xpad, ypad; + + size = 16; // fallback used by GtkFileChooserWidget + if (gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &width, &height) != FALSE) + size = MAX(width, height); + gtk_cell_renderer_get_padding(r, &xpad, &ypad); + gtk_cell_renderer_set_fixed_size(r, + 2 * xpad + size, + 2 * ypad + size); +} + +static void applyColor(GtkTreeModel *m, GtkTreeIter *iter, int modelColumn, GtkCellRenderer *r, const char *prop, const char *propSet) +{ + GValue value = G_VALUE_INIT; + GdkRGBA *rgba; + + gtk_tree_model_get_value(m, iter, modelColumn, &value); + rgba = (GdkRGBA *) g_value_get_boxed(&value); + if (rgba != NULL) + g_object_set(r, prop, rgba, NULL); + else + g_object_set(r, propSet, FALSE, NULL); + g_value_unset(&value); +} + +static void setEditable(uiTableModel *m, GtkTreeIter *iter, int modelColumn, GtkCellRenderer *r, const char *prop) +{ + GtkTreePath *path; + int row; + gboolean editable; + + // TODO avoid the need for this + path = gtk_tree_model_get_path(GTK_TREE_MODEL(m), iter); + row = gtk_tree_path_get_indices(path)[0]; + gtk_tree_path_free(path); + editable = uiprivTableModelCellEditable(m, row, modelColumn) != 0; + g_object_set(r, prop, editable, NULL); +} + +static void applyBackgroundColor(uiTable *t, GtkTreeModel *m, GtkTreeIter *iter, GtkCellRenderer *r) +{ + if (t->backgroundColumn != -1) + applyColor(m, iter, t->backgroundColumn, + r, "cell-background-rgba", "cell-background-set"); +} + +static void onEdited(uiTableModel *m, int column, const char *pathstr, const uiTableValue *tvalue, GtkTreeIter *iter) +{ + GtkTreePath *path; + int row; + + path = gtk_tree_path_new_from_string(pathstr); + row = gtk_tree_path_get_indices(path)[0]; + if (iter != NULL) + gtk_tree_model_get_iter(GTK_TREE_MODEL(m), iter, path); + gtk_tree_path_free(path); + uiprivTableModelSetCellValue(m, row, column, tvalue); +} + +struct textColumnParams { + uiTable *t; + uiTableModel *m; + int modelColumn; + int editableColumn; + uiTableTextColumnOptionalParams params; +}; + +static void textColumnDataFunc(GtkTreeViewColumn *c, GtkCellRenderer *r, GtkTreeModel *m, GtkTreeIter *iter, gpointer data) +{ + struct textColumnParams *p = (struct textColumnParams *) data; + GValue value = G_VALUE_INIT; + const gchar *str; + + gtk_tree_model_get_value(m, iter, p->modelColumn, &value); + str = g_value_get_string(&value); + g_object_set(r, "text", str, NULL); + g_value_unset(&value); + + setEditable(p->m, iter, p->editableColumn, r, "editable"); + + if (p->params.ColorModelColumn != -1) + applyColor(m, iter, p->params.ColorModelColumn, + r, "foreground-rgba", "foreground-set"); + + applyBackgroundColor(p->t, m, iter, r); +} + +static void textColumnEdited(GtkCellRendererText *r, gchar *path, gchar *newText, gpointer data) +{ + struct textColumnParams *p = (struct textColumnParams *) data; + uiTableValue *tvalue; + GtkTreeIter iter; + + tvalue = uiNewTableValueString(newText); + onEdited(p->m, p->modelColumn, path, tvalue, &iter); + uiFreeTableValue(tvalue); + // and update the column TODO copy comment here + textColumnDataFunc(NULL, GTK_CELL_RENDERER(r), GTK_TREE_MODEL(p->m), &iter, data); +} + +struct imageColumnParams { + uiTable *t; + int modelColumn; +}; + +static void imageColumnDataFunc(GtkTreeViewColumn *c, GtkCellRenderer *r, GtkTreeModel *m, GtkTreeIter *iter, gpointer data) +{ + struct imageColumnParams *p = (struct imageColumnParams *) data; + GValue value = G_VALUE_INIT; + uiImage *img; + +//TODO setImageSize(r); + gtk_tree_model_get_value(m, iter, p->modelColumn, &value); + img = (uiImage *) g_value_get_pointer(&value); + g_object_set(r, "surface", + uiprivImageAppropriateSurface(img, p->t->treeWidget), + NULL); + g_value_unset(&value); + + applyBackgroundColor(p->t, m, iter, r); +} + +struct checkboxColumnParams { + uiTable *t; + uiTableModel *m; + int modelColumn; + int editableColumn; +}; + +static void checkboxColumnDataFunc(GtkTreeViewColumn *c, GtkCellRenderer *r, GtkTreeModel *m, GtkTreeIter *iter, gpointer data) +{ + struct checkboxColumnParams *p = (struct checkboxColumnParams *) data; + GValue value = G_VALUE_INIT; + gboolean active; + + gtk_tree_model_get_value(m, iter, p->modelColumn, &value); + active = g_value_get_int(&value) != 0; + g_object_set(r, "active", active, NULL); + g_value_unset(&value); + + setEditable(p->m, iter, p->editableColumn, r, "activatable"); + + applyBackgroundColor(p->t, m, iter, r); +} + +static void checkboxColumnToggled(GtkCellRendererToggle *r, gchar *pathstr, gpointer data) +{ + struct checkboxColumnParams *p = (struct checkboxColumnParams *) data; + GValue value = G_VALUE_INIT; + int v; + uiTableValue *tvalue; + GtkTreePath *path; + GtkTreeIter iter; + + path = gtk_tree_path_new_from_string(pathstr); + gtk_tree_model_get_iter(GTK_TREE_MODEL(p->m), &iter, path); + gtk_tree_path_free(path); + gtk_tree_model_get_value(GTK_TREE_MODEL(p->m), &iter, p->modelColumn, &value); + v = g_value_get_int(&value); + g_value_unset(&value); + tvalue = uiNewTableValueInt(!v); + onEdited(p->m, p->modelColumn, pathstr, tvalue, NULL); + uiFreeTableValue(tvalue); + // and update the column TODO copy comment here + // TODO avoid fetching the model data twice + checkboxColumnDataFunc(NULL, GTK_CELL_RENDERER(r), GTK_TREE_MODEL(p->m), &iter, data); +} + +struct progressBarColumnParams { + uiTable *t; + int modelColumn; +}; + +struct rowcol { + int row; + int col; +}; + +static guint rowcolHash(gconstpointer key) +{ + const struct rowcol *rc = (const struct rowcol *) key; + guint row, col; + + row = (guint) (rc->row); + col = (guint) (rc->col); + return row ^ col; +} + +static gboolean rowcolEqual(gconstpointer a, gconstpointer b) +{ + const struct rowcol *ra = (const struct rowcol *) a; + const struct rowcol *rb = (const struct rowcol *) b; + + return (ra->row == rb->row) && (ra->col == rb->col); +} + +static void pulseOne(gpointer key, gpointer value, gpointer data) +{ + uiTable *t = uiTable(data); + struct rowcol *rc = (struct rowcol *) key; + + // TODO this is bad: it produces changed handlers for every table because that's how GtkTreeModel works, yet this is per-table because that's how it works + // however, a proper fix would require decoupling progress from normal integers, which we could do... + uiTableModelRowChanged(t->model, rc->row); +} + +static gboolean indeterminatePulse(gpointer data) +{ + uiTable *t = uiTable(data); + + g_hash_table_foreach(t->indeterminatePositions, pulseOne, t); + return TRUE; +} + +static void progressBarColumnDataFunc(GtkTreeViewColumn *c, GtkCellRenderer *r, GtkTreeModel *m, GtkTreeIter *iter, gpointer data) +{ + struct progressBarColumnParams *p = (struct progressBarColumnParams *) data; + GValue value = G_VALUE_INIT; + int pval; + struct rowcol *rc; + gint *val; + GtkTreePath *path; + + gtk_tree_model_get_value(m, iter, p->modelColumn, &value); + pval = g_value_get_int(&value); + rc = uiprivNew(struct rowcol); + // TODO avoid the need for this + path = gtk_tree_model_get_path(GTK_TREE_MODEL(m), iter); + rc->row = gtk_tree_path_get_indices(path)[0]; + gtk_tree_path_free(path); + rc->col = p->modelColumn; + val = (gint *) g_hash_table_lookup(p->t->indeterminatePositions, rc); + if (pval == -1) { + if (val == NULL) { + val = uiprivNew(gint); + *val = 1; + g_hash_table_insert(p->t->indeterminatePositions, rc, val); + } else { + uiprivFree(rc); + (*val)++; + if (*val == G_MAXINT) + *val = 1; + } + g_object_set(r, + "pulse", *val, + NULL); + if (p->t->indeterminateTimer == 0) + // TODO verify the timeout + p->t->indeterminateTimer = g_timeout_add(100, indeterminatePulse, p->t); + } else { + if (val != NULL) { + g_hash_table_remove(p->t->indeterminatePositions, rc); + if (g_hash_table_size(p->t->indeterminatePositions) == 0) { + g_source_remove(p->t->indeterminateTimer); + p->t->indeterminateTimer = 0; + } + } + uiprivFree(rc); + g_object_set(r, + "pulse", -1, + "value", pval, + NULL); + } + g_value_unset(&value); + + applyBackgroundColor(p->t, m, iter, r); +} + +struct buttonColumnParams { + uiTable *t; + uiTableModel *m; + int modelColumn; + int clickableColumn; +}; + +static void buttonColumnDataFunc(GtkTreeViewColumn *c, GtkCellRenderer *r, GtkTreeModel *m, GtkTreeIter *iter, gpointer data) +{ + struct buttonColumnParams *p = (struct buttonColumnParams *) data; + GValue value = G_VALUE_INIT; + const gchar *str; + + gtk_tree_model_get_value(m, iter, p->modelColumn, &value); + str = g_value_get_string(&value); + g_object_set(r, "text", str, NULL); + g_value_unset(&value); + + setEditable(p->m, iter, p->clickableColumn, r, "sensitive"); + + applyBackgroundColor(p->t, m, iter, r); +} + +// TODO wrong type here +static void buttonColumnClicked(GtkCellRenderer *r, gchar *pathstr, gpointer data) +{ + struct buttonColumnParams *p = (struct buttonColumnParams *) data; + + onEdited(p->m, p->modelColumn, pathstr, NULL, NULL); +} + +static GtkTreeViewColumn *addColumn(uiTable *t, const char *name) +{ + GtkTreeViewColumn *c; + + c = gtk_tree_view_column_new(); + gtk_tree_view_column_set_resizable(c, TRUE); + gtk_tree_view_column_set_title(c, name); + gtk_tree_view_append_column(t->tv, c); + return c; +} + +static void addTextColumn(uiTable *t, GtkTreeViewColumn *c, int textModelColumn, int textEditableModelColumn, uiTableTextColumnOptionalParams *textParams) +{ + struct textColumnParams *p; + GtkCellRenderer *r; + + p = uiprivNew(struct textColumnParams); + p->t = t; + // TODO get rid of these fields AND rename t->model in favor of t->m + p->m = t->model; + p->modelColumn = textModelColumn; + p->editableColumn = textEditableModelColumn; + if (textParams != NULL) + p->params = *textParams; + else + p->params = uiprivDefaultTextColumnOptionalParams; + + r = gtk_cell_renderer_text_new(); + gtk_tree_view_column_pack_start(c, r, TRUE); + gtk_tree_view_column_set_cell_data_func(c, r, textColumnDataFunc, p, NULL); + g_signal_connect(r, "edited", G_CALLBACK(textColumnEdited), p); + g_ptr_array_add(t->columnParams, p); +} + +// TODO rename modelCOlumn and params everywhere +void uiTableAppendTextColumn(uiTable *t, const char *name, int textModelColumn, int textEditableModelColumn, uiTableTextColumnOptionalParams *textParams) +{ + GtkTreeViewColumn *c; + + c = addColumn(t, name); + addTextColumn(t, c, textModelColumn, textEditableModelColumn, textParams); +} + +static void addImageColumn(uiTable *t, GtkTreeViewColumn *c, int imageModelColumn) +{ + struct imageColumnParams *p; + GtkCellRenderer *r; + + p = uiprivNew(struct imageColumnParams); + p->t = t; + p->modelColumn = imageModelColumn; + + r = gtk_cell_renderer_pixbuf_new(); + gtk_tree_view_column_pack_start(c, r, FALSE); + gtk_tree_view_column_set_cell_data_func(c, r, imageColumnDataFunc, p, NULL); + g_ptr_array_add(t->columnParams, p); +} + +void uiTableAppendImageColumn(uiTable *t, const char *name, int imageModelColumn) +{ + GtkTreeViewColumn *c; + + c = addColumn(t, name); + addImageColumn(t, c, imageModelColumn); +} + +void uiTableAppendImageTextColumn(uiTable *t, const char *name, int imageModelColumn, int textModelColumn, int textEditableModelColumn, uiTableTextColumnOptionalParams *textParams) +{ + GtkTreeViewColumn *c; + + c = addColumn(t, name); + addImageColumn(t, c, imageModelColumn); + addTextColumn(t, c, textModelColumn, textEditableModelColumn, textParams); +} + +static void addCheckboxColumn(uiTable *t, GtkTreeViewColumn *c, int checkboxModelColumn, int checkboxEditableModelColumn) +{ + struct checkboxColumnParams *p; + GtkCellRenderer *r; + + p = uiprivNew(struct checkboxColumnParams); + p->t = t; + p->m = t->model; + p->modelColumn = checkboxModelColumn; + p->editableColumn = checkboxEditableModelColumn; + + r = gtk_cell_renderer_toggle_new(); + gtk_tree_view_column_pack_start(c, r, FALSE); + gtk_tree_view_column_set_cell_data_func(c, r, checkboxColumnDataFunc, p, NULL); + g_signal_connect(r, "toggled", G_CALLBACK(checkboxColumnToggled), p); + g_ptr_array_add(t->columnParams, p); +} + +void uiTableAppendCheckboxColumn(uiTable *t, const char *name, int checkboxModelColumn, int checkboxEditableModelColumn) +{ + GtkTreeViewColumn *c; + + c = addColumn(t, name); + addCheckboxColumn(t, c, checkboxModelColumn, checkboxEditableModelColumn); +} + +void uiTableAppendCheckboxTextColumn(uiTable *t, const char *name, int checkboxModelColumn, int checkboxEditableModelColumn, int textModelColumn, int textEditableModelColumn, uiTableTextColumnOptionalParams *textParams) +{ + GtkTreeViewColumn *c; + + c = addColumn(t, name); + addCheckboxColumn(t, c, checkboxModelColumn, checkboxEditableModelColumn); + addTextColumn(t, c, textModelColumn, textEditableModelColumn, textParams); +} + +void uiTableAppendProgressBarColumn(uiTable *t, const char *name, int progressModelColumn) +{ + GtkTreeViewColumn *c; + struct progressBarColumnParams *p; + GtkCellRenderer *r; + + c = addColumn(t, name); + + p = uiprivNew(struct progressBarColumnParams); + p->t = t; + // TODO make progress and progressBar consistent everywhere + p->modelColumn = progressModelColumn; + + r = gtk_cell_renderer_progress_new(); + gtk_tree_view_column_pack_start(c, r, TRUE); + gtk_tree_view_column_set_cell_data_func(c, r, progressBarColumnDataFunc, p, NULL); + g_ptr_array_add(t->columnParams, p); +} + +void uiTableAppendButtonColumn(uiTable *t, const char *name, int buttonModelColumn, int buttonClickableModelColumn) +{ + GtkTreeViewColumn *c; + struct buttonColumnParams *p; + GtkCellRenderer *r; + + c = addColumn(t, name); + + p = uiprivNew(struct buttonColumnParams); + p->t = t; + p->m = t->model; + p->modelColumn = buttonModelColumn; + p->clickableColumn = buttonClickableModelColumn; + + r = uiprivNewCellRendererButton(); + gtk_tree_view_column_pack_start(c, r, TRUE); + gtk_tree_view_column_set_cell_data_func(c, r, buttonColumnDataFunc, p, NULL); + g_signal_connect(r, "clicked", G_CALLBACK(buttonColumnClicked), p); + g_ptr_array_add(t->columnParams, p); +} + +uiUnixControlAllDefaultsExceptDestroy(uiTable) + +static void uiTableDestroy(uiControl *c) +{ + uiTable *t = uiTable(c); + guint i; + + for (i = 0; i < t->columnParams->len; i++) + uiprivFree(g_ptr_array_index(t->columnParams, i)); + g_ptr_array_free(t->columnParams, TRUE); + if (g_hash_table_size(t->indeterminatePositions) != 0) + g_source_remove(t->indeterminateTimer); + g_hash_table_destroy(t->indeterminatePositions); + g_object_unref(t->widget); + uiFreeControl(uiControl(t)); +} + +uiTable *uiNewTable(uiTableParams *p) +{ + uiTable *t; + + uiUnixNewControl(uiTable, t); + + t->model = p->Model; + t->columnParams = g_ptr_array_new(); + t->backgroundColumn = p->RowBackgroundColorModelColumn; + + t->widget = gtk_scrolled_window_new(NULL, NULL); + t->scontainer = GTK_CONTAINER(t->widget); + t->sw = GTK_SCROLLED_WINDOW(t->widget); + gtk_scrolled_window_set_shadow_type(t->sw, GTK_SHADOW_IN); + + t->treeWidget = gtk_tree_view_new_with_model(GTK_TREE_MODEL(t->model)); + t->tv = GTK_TREE_VIEW(t->treeWidget); + // TODO set up t->tv + + gtk_container_add(t->scontainer, t->treeWidget); + // and make the tree view visible; only the scrolled window's visibility is controlled by libui + gtk_widget_show(t->treeWidget); + + t->indeterminatePositions = g_hash_table_new_full(rowcolHash, rowcolEqual, + uiprivFree, uiprivFree); + + return t; +} diff --git a/dep/libui/unix/table.h b/dep/libui/unix/table.h new file mode 100644 index 0000000..af7e954 --- /dev/null +++ b/dep/libui/unix/table.h @@ -0,0 +1,19 @@ +// 4 june 2018 +#include "../common/table.h" + +// tablemodel.c +#define uiTableModelType (uiTableModel_get_type()) +#define uiTableModel(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), uiTableModelType, uiTableModel)) +#define isuiTableModel(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), uiTableModelType)) +#define uiTableModelClass(class) (G_TYPE_CHECK_CLASS_CAST((class), uiTableModelType, uiTableModelClass)) +#define isuiTableModelClass(class) (G_TYPE_CHECK_CLASS_TYPE((class), uiTableModel)) +#define getuiTableModelClass(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), uiTableModelType, uiTableModelClass)) +typedef struct uiTableModelClass uiTableModelClass; +struct uiTableModel { + GObject parent_instance; + uiTableModelHandler *mh; +}; +struct uiTableModelClass { + GObjectClass parent_class; +}; +extern GType uiTableModel_get_type(void); diff --git a/dep/libui/unix/tablemodel.c b/dep/libui/unix/tablemodel.c new file mode 100644 index 0000000..ee957b5 --- /dev/null +++ b/dep/libui/unix/tablemodel.c @@ -0,0 +1,288 @@ +// 26 june 2016 +#include "uipriv_unix.h" +#include "table.h" + +static void uiTableModel_gtk_tree_model_interface_init(GtkTreeModelIface *iface); + +G_DEFINE_TYPE_WITH_CODE(uiTableModel, uiTableModel, G_TYPE_OBJECT, + G_IMPLEMENT_INTERFACE(GTK_TYPE_TREE_MODEL, uiTableModel_gtk_tree_model_interface_init)) + +static void uiTableModel_init(uiTableModel *m) +{ + // nothing to do +} + +static void uiTableModel_dispose(GObject *obj) +{ + G_OBJECT_CLASS(uiTableModel_parent_class)->dispose(obj); +} + +static void uiTableModel_finalize(GObject *obj) +{ + G_OBJECT_CLASS(uiTableModel_parent_class)->finalize(obj); +} + +static GtkTreeModelFlags uiTableModel_get_flags(GtkTreeModel *mm) +{ + return GTK_TREE_MODEL_LIST_ONLY; +} + +static gint uiTableModel_get_n_columns(GtkTreeModel *mm) +{ + uiTableModel *m = uiTableModel(mm); + + return uiprivTableModelNumColumns(m); +} + +static GType uiTableModel_get_column_type(GtkTreeModel *mm, gint index) +{ + uiTableModel *m = uiTableModel(mm); + + switch (uiprivTableModelColumnType(m, index)) { + case uiTableValueTypeString: + return G_TYPE_STRING; + case uiTableValueTypeImage: + return G_TYPE_POINTER; + case uiTableValueTypeInt: + return G_TYPE_INT; + case uiTableValueTypeColor: + return GDK_TYPE_RGBA; + } + // TODO + return G_TYPE_INVALID; +} + +#define STAMP_GOOD 0x1234 +#define STAMP_BAD 0x5678 + +static gboolean uiTableModel_get_iter(GtkTreeModel *mm, GtkTreeIter *iter, GtkTreePath *path) +{ + uiTableModel *m = uiTableModel(mm); + gint row; + + if (gtk_tree_path_get_depth(path) != 1) + goto bad; + row = gtk_tree_path_get_indices(path)[0]; + if (row < 0) + goto bad; + if (row >= uiprivTableModelNumRows(m)) + goto bad; + iter->stamp = STAMP_GOOD; + iter->user_data = GINT_TO_POINTER(row); + return TRUE; +bad: + iter->stamp = STAMP_BAD; + return FALSE; +} + +// GtkListStore returns NULL on error; let's do that too +static GtkTreePath *uiTableModel_get_path(GtkTreeModel *mm, GtkTreeIter *iter) +{ + gint row; + + if (iter->stamp != STAMP_GOOD) + return NULL; + row = GPOINTER_TO_INT(iter->user_data); + return gtk_tree_path_new_from_indices(row, -1); +} + +// GtkListStore leaves value empty on failure; let's do the same +static void uiTableModel_get_value(GtkTreeModel *mm, GtkTreeIter *iter, gint column, GValue *value) +{ + uiTableModel *m = uiTableModel(mm); + gint row; + uiTableValue *tvalue; + double r, g, b, a; + GdkRGBA rgba; + + if (iter->stamp != STAMP_GOOD) + return; + row = GPOINTER_TO_INT(iter->user_data); + tvalue = uiprivTableModelCellValue(m, row, column); + switch (uiprivTableModelColumnType(m, column)) { + case uiTableValueTypeString: + g_value_init(value, G_TYPE_STRING); + g_value_set_string(value, uiTableValueString(tvalue)); + uiFreeTableValue(tvalue); + return; + case uiTableValueTypeImage: + g_value_init(value, G_TYPE_POINTER); + g_value_set_pointer(value, uiTableValueImage(tvalue)); + uiFreeTableValue(tvalue); + return; + case uiTableValueTypeInt: + g_value_init(value, G_TYPE_INT); + g_value_set_int(value, uiTableValueInt(tvalue)); + uiFreeTableValue(tvalue); + return; + case uiTableValueTypeColor: + g_value_init(value, GDK_TYPE_RGBA); + if (tvalue == NULL) { + g_value_set_boxed(value, NULL); + return; + } + uiTableValueColor(tvalue, &r, &g, &b, &a); + uiFreeTableValue(tvalue); + rgba.red = r; + rgba.green = g; + rgba.blue = b; + rgba.alpha = a; + g_value_set_boxed(value, &rgba); + return; + } + // TODO +} + +static gboolean uiTableModel_iter_next(GtkTreeModel *mm, GtkTreeIter *iter) +{ + uiTableModel *m = uiTableModel(mm); + gint row; + + if (iter->stamp != STAMP_GOOD) + return FALSE; + row = GPOINTER_TO_INT(iter->user_data); + row++; + if (row >= uiprivTableModelNumRows(m)) { + iter->stamp = STAMP_BAD; + return FALSE; + } + iter->user_data = GINT_TO_POINTER(row); + return TRUE; +} + +static gboolean uiTableModel_iter_previous(GtkTreeModel *mm, GtkTreeIter *iter) +{ + gint row; + + if (iter->stamp != STAMP_GOOD) + return FALSE; + row = GPOINTER_TO_INT(iter->user_data); + row--; + if (row < 0) { + iter->stamp = STAMP_BAD; + return FALSE; + } + iter->user_data = GINT_TO_POINTER(row); + return TRUE; +} + +static gboolean uiTableModel_iter_children(GtkTreeModel *mm, GtkTreeIter *iter, GtkTreeIter *parent) +{ + return gtk_tree_model_iter_nth_child(mm, iter, parent, 0); +} + +static gboolean uiTableModel_iter_has_child(GtkTreeModel *mm, GtkTreeIter *iter) +{ + return FALSE; +} + +static gint uiTableModel_iter_n_children(GtkTreeModel *mm, GtkTreeIter *iter) +{ + uiTableModel *m = uiTableModel(mm); + + if (iter != NULL) + return 0; + return uiprivTableModelNumRows(m); +} + +static gboolean uiTableModel_iter_nth_child(GtkTreeModel *mm, GtkTreeIter *iter, GtkTreeIter *parent, gint n) +{ + uiTableModel *m = uiTableModel(mm); + + if (iter->stamp != STAMP_GOOD) + return FALSE; + if (parent != NULL) + goto bad; + if (n < 0) + goto bad; + if (n >= uiprivTableModelNumRows(m)) + goto bad; + iter->stamp = STAMP_GOOD; + iter->user_data = GINT_TO_POINTER(n); + return TRUE; +bad: + iter->stamp = STAMP_BAD; + return FALSE; +} + +gboolean uiTableModel_iter_parent(GtkTreeModel *mm, GtkTreeIter *iter, GtkTreeIter *child) +{ + iter->stamp = STAMP_BAD; + return FALSE; +} + +static void uiTableModel_class_init(uiTableModelClass *class) +{ + G_OBJECT_CLASS(class)->dispose = uiTableModel_dispose; + G_OBJECT_CLASS(class)->finalize = uiTableModel_finalize; +} + +static void uiTableModel_gtk_tree_model_interface_init(GtkTreeModelIface *iface) +{ + iface->get_flags = uiTableModel_get_flags; + iface->get_n_columns = uiTableModel_get_n_columns; + iface->get_column_type = uiTableModel_get_column_type; + iface->get_iter = uiTableModel_get_iter; + iface->get_path = uiTableModel_get_path; + iface->get_value = uiTableModel_get_value; + iface->iter_next = uiTableModel_iter_next; + iface->iter_previous = uiTableModel_iter_previous; + iface->iter_children = uiTableModel_iter_children; + iface->iter_has_child = uiTableModel_iter_has_child; + iface->iter_n_children = uiTableModel_iter_n_children; + iface->iter_nth_child = uiTableModel_iter_nth_child; + iface->iter_parent = uiTableModel_iter_parent; + // don't specify ref_node() or unref_node() +} + +uiTableModel *uiNewTableModel(uiTableModelHandler *mh) +{ + uiTableModel *m; + + m = uiTableModel(g_object_new(uiTableModelType, NULL)); + m->mh = mh; + return m; +} + +void uiFreeTableModel(uiTableModel *m) +{ + g_object_unref(m); +} + +void uiTableModelRowInserted(uiTableModel *m, int newIndex) +{ + GtkTreePath *path; + GtkTreeIter iter; + + path = gtk_tree_path_new_from_indices(newIndex, -1); + iter.stamp = STAMP_GOOD; + iter.user_data = GINT_TO_POINTER(newIndex); + gtk_tree_model_row_inserted(GTK_TREE_MODEL(m), path, &iter); + gtk_tree_path_free(path); +} + +void uiTableModelRowChanged(uiTableModel *m, int index) +{ + GtkTreePath *path; + GtkTreeIter iter; + + path = gtk_tree_path_new_from_indices(index, -1); + iter.stamp = STAMP_GOOD; + iter.user_data = GINT_TO_POINTER(index); + gtk_tree_model_row_changed(GTK_TREE_MODEL(m), path, &iter); + gtk_tree_path_free(path); +} + +void uiTableModelRowDeleted(uiTableModel *m, int oldIndex) +{ + GtkTreePath *path; + + path = gtk_tree_path_new_from_indices(oldIndex, -1); + gtk_tree_model_row_deleted(GTK_TREE_MODEL(m), path); + gtk_tree_path_free(path); +} + +uiTableModelHandler *uiprivTableModelHandler(uiTableModel *m) +{ + return m->mh; +} diff --git a/dep/libui/unix/text.c b/dep/libui/unix/text.c new file mode 100644 index 0000000..9a2a9dc --- /dev/null +++ b/dep/libui/unix/text.c @@ -0,0 +1,17 @@ +// 9 april 2015 +#include "uipriv_unix.h" + +char *uiUnixStrdupText(const char *t) +{ + return g_strdup(t); +} + +void uiFreeText(char *t) +{ + g_free(t); +} + +int uiprivStricmp(const char *a, const char *b) +{ + return strcasecmp(a, b); +} diff --git a/dep/libui/unix/uipriv_unix.h b/dep/libui/unix/uipriv_unix.h new file mode 100644 index 0000000..de604ce --- /dev/null +++ b/dep/libui/unix/uipriv_unix.h @@ -0,0 +1,61 @@ +// 22 april 2015 +#define GLIB_VERSION_MIN_REQUIRED GLIB_VERSION_2_40 +#define GLIB_VERSION_MAX_ALLOWED GLIB_VERSION_2_40 +#define GDK_VERSION_MIN_REQUIRED GDK_VERSION_3_10 +#define GDK_VERSION_MAX_ALLOWED GDK_VERSION_3_10 +#include +#include +#include // see future.c +#include +#include +#include +#include +#include "../ui.h" +#include "../ui_unix.h" +#include "../common/uipriv.h" + +#define uiprivGTKXMargin 12 +#define uiprivGTKYMargin 12 +#define uiprivGTKXPadding 12 +#define uiprivGTKYPadding 6 + +// menu.c +extern GtkWidget *uiprivMakeMenubar(uiWindow *); +extern void uiprivFreeMenubar(GtkWidget *); +extern void uiprivUninitMenus(void); + +// alloc.c +extern void uiprivInitAlloc(void); +extern void uiprivUninitAlloc(void); + +// util.c +extern void uiprivSetMargined(GtkContainer *, int); + +// child.c +typedef struct uiprivChild uiprivChild; +extern uiprivChild *uiprivNewChild(uiControl *child, uiControl *parent, GtkContainer *parentContainer); +extern uiprivChild *uiprivNewChildWithBox(uiControl *child, uiControl *parent, GtkContainer *parentContainer, int margined); +extern void uiprivChildRemove(uiprivChild *c); +extern void uiprivChildDestroy(uiprivChild *c); +extern GtkWidget *uiprivChildWidget(uiprivChild *c); +extern int uiprivChildFlag(uiprivChild *c); +extern void uiprivChildSetFlag(uiprivChild *c, int flag); +extern GtkWidget *uiprivChildBox(uiprivChild *c); +extern void uiprivChildSetMargined(uiprivChild *c, int margined); + +// draw.c +extern uiDrawContext *uiprivNewContext(cairo_t *cr, GtkStyleContext *style); +extern void uiprivFreeContext(uiDrawContext *); + +// image.c +extern cairo_surface_t *uiprivImageAppropriateSurface(uiImage *i, GtkWidget *w); + +// cellrendererbutton.c +extern GtkCellRenderer *uiprivNewCellRendererButton(void); + +// future.c +extern void uiprivLoadFutures(void); +extern PangoAttribute *uiprivFUTURE_pango_attr_font_features_new(const gchar *features); +extern PangoAttribute *uiprivFUTURE_pango_attr_foreground_alpha_new(guint16 alpha); +extern PangoAttribute *uiprivFUTURE_pango_attr_background_alpha_new(guint16 alpha); +extern gboolean uiprivFUTURE_gtk_widget_path_iter_set_object_name(GtkWidgetPath *path, gint pos, const char *name); diff --git a/dep/libui/unix/util.c b/dep/libui/unix/util.c new file mode 100644 index 0000000..f3929cc --- /dev/null +++ b/dep/libui/unix/util.c @@ -0,0 +1,10 @@ +// 18 april 2015 +#include "uipriv_unix.h" + +void uiprivSetMargined(GtkContainer *c, int margined) +{ + if (margined) + gtk_container_set_border_width(c, uiprivGTKXMargin); + else + gtk_container_set_border_width(c, 0); +} diff --git a/dep/libui/unix/window.c b/dep/libui/unix/window.c new file mode 100644 index 0000000..c5ba203 --- /dev/null +++ b/dep/libui/unix/window.c @@ -0,0 +1,279 @@ +// 11 june 2015 +#include "uipriv_unix.h" + +struct uiWindow { + uiUnixControl c; + + GtkWidget *widget; + GtkContainer *container; + GtkWindow *window; + + GtkWidget *vboxWidget; + GtkContainer *vboxContainer; + GtkBox *vbox; + + GtkWidget *childHolderWidget; + GtkContainer *childHolderContainer; + + GtkWidget *menubar; + + uiControl *child; + int margined; + + int (*onClosing)(uiWindow *, void *); + void *onClosingData; + void (*onContentSizeChanged)(uiWindow *, void *); + void *onContentSizeChangedData; + gboolean fullscreen; +}; + +static gboolean onClosing(GtkWidget *win, GdkEvent *e, gpointer data) +{ + uiWindow *w = uiWindow(data); + + // manually destroy the window ourselves; don't let the delete-event handler do it + if ((*(w->onClosing))(w, w->onClosingData)) + uiControlDestroy(uiControl(w)); + // don't continue to the default delete-event handler; we destroyed the window by now + return TRUE; +} + +static void onSizeAllocate(GtkWidget *widget, GdkRectangle *allocation, gpointer data) +{ + uiWindow *w = uiWindow(data); + + // TODO deal with spurious size-allocates + (*(w->onContentSizeChanged))(w, w->onContentSizeChangedData); +} + +static int defaultOnClosing(uiWindow *w, void *data) +{ + return 0; +} + +static void defaultOnPositionContentSizeChanged(uiWindow *w, void *data) +{ + // do nothing +} + +static void uiWindowDestroy(uiControl *c) +{ + uiWindow *w = uiWindow(c); + + // first hide ourselves + gtk_widget_hide(w->widget); + // now destroy the child + if (w->child != NULL) { + uiControlSetParent(w->child, NULL); + uiUnixControlSetContainer(uiUnixControl(w->child), w->childHolderContainer, TRUE); + uiControlDestroy(w->child); + } + // now destroy the menus, if any + if (w->menubar != NULL) + uiprivFreeMenubar(w->menubar); + gtk_widget_destroy(w->childHolderWidget); + gtk_widget_destroy(w->vboxWidget); + // and finally free ourselves + // use gtk_widget_destroy() instead of g_object_unref() because GTK+ has internal references (see #165) + gtk_widget_destroy(w->widget); + uiFreeControl(uiControl(w)); +} + +uiUnixControlDefaultHandle(uiWindow) + +uiControl *uiWindowParent(uiControl *c) +{ + return NULL; +} + +void uiWindowSetParent(uiControl *c, uiControl *parent) +{ + uiUserBugCannotSetParentOnToplevel("uiWindow"); +} + +static int uiWindowToplevel(uiControl *c) +{ + return 1; +} + +uiUnixControlDefaultVisible(uiWindow) + +static void uiWindowShow(uiControl *c) +{ + uiWindow *w = uiWindow(c); + + // don't use gtk_widget_show_all() as that will show all children, regardless of user settings + // don't use gtk_widget_show(); that doesn't bring to front or give keyboard focus + // (gtk_window_present() does call gtk_widget_show() though) + gtk_window_present(w->window); +} + +uiUnixControlDefaultHide(uiWindow) +uiUnixControlDefaultEnabled(uiWindow) +uiUnixControlDefaultEnable(uiWindow) +uiUnixControlDefaultDisable(uiWindow) +// TODO? +uiUnixControlDefaultSetContainer(uiWindow) + +char *uiWindowTitle(uiWindow *w) +{ + return uiUnixStrdupText(gtk_window_get_title(w->window)); +} + +void uiWindowSetTitle(uiWindow *w, const char *title) +{ + gtk_window_set_title(w->window, title); +} + +void uiWindowContentSize(uiWindow *w, int *width, int *height) +{ + GtkAllocation allocation; + + gtk_widget_get_allocation(w->childHolderWidget, &allocation); + *width = allocation.width; + *height = allocation.height; +} + +void uiWindowSetContentSize(uiWindow *w, int width, int height) +{ + GtkAllocation childAlloc; + gint winWidth, winHeight; + + // we need to resize the child holder widget to the given size + // we can't resize that without running the event loop + // but we can do gtk_window_set_size() + // so how do we deal with the differences in sizes? + // simple arithmetic, of course! + + // from what I can tell, the return from gtk_widget_get_allocation(w->window) and gtk_window_get_size(w->window) will be the same + // this is not affected by Wayland and not affected by GTK+ builtin CSD + // so we can safely juse use them to get the real window size! + // since we're using gtk_window_resize(), use the latter + gtk_window_get_size(w->window, &winWidth, &winHeight); + + // now get the child holder widget's current allocation + gtk_widget_get_allocation(w->childHolderWidget, &childAlloc); + // and punch that out of the window size + winWidth -= childAlloc.width; + winHeight -= childAlloc.height; + + // now we just need to add the new size back in + winWidth += width; + winHeight += height; + // and set it + // this will not move the window in my tests, so we're good + gtk_window_resize(w->window, winWidth, winHeight); +} + +int uiWindowFullscreen(uiWindow *w) +{ + return w->fullscreen; +} + +// TODO use window-state-event to track +// TODO does this send an extra size changed? +// TODO what behavior do we want? +void uiWindowSetFullscreen(uiWindow *w, int fullscreen) +{ + w->fullscreen = fullscreen; + if (w->fullscreen) + gtk_window_fullscreen(w->window); + else + gtk_window_unfullscreen(w->window); +} + +void uiWindowOnContentSizeChanged(uiWindow *w, void (*f)(uiWindow *, void *), void *data) +{ + w->onContentSizeChanged = f; + w->onContentSizeChangedData = data; +} + +void uiWindowOnClosing(uiWindow *w, int (*f)(uiWindow *, void *), void *data) +{ + w->onClosing = f; + w->onClosingData = data; +} + +int uiWindowBorderless(uiWindow *w) +{ + return gtk_window_get_decorated(w->window) == FALSE; +} + +void uiWindowSetBorderless(uiWindow *w, int borderless) +{ + gtk_window_set_decorated(w->window, borderless == 0); +} + +// TODO save and restore expands and aligns +void uiWindowSetChild(uiWindow *w, uiControl *child) +{ + if (w->child != NULL) { + uiControlSetParent(w->child, NULL); + uiUnixControlSetContainer(uiUnixControl(w->child), w->childHolderContainer, TRUE); + } + w->child = child; + if (w->child != NULL) { + uiControlSetParent(w->child, uiControl(w)); + uiUnixControlSetContainer(uiUnixControl(w->child), w->childHolderContainer, FALSE); + } +} + +int uiWindowMargined(uiWindow *w) +{ + return w->margined; +} + +void uiWindowSetMargined(uiWindow *w, int margined) +{ + w->margined = margined; + uiprivSetMargined(w->childHolderContainer, w->margined); +} + +uiWindow *uiNewWindow(const char *title, int width, int height, int hasMenubar) +{ + uiWindow *w; + + uiUnixNewControl(uiWindow, w); + + w->widget = gtk_window_new(GTK_WINDOW_TOPLEVEL); + w->container = GTK_CONTAINER(w->widget); + w->window = GTK_WINDOW(w->widget); + + gtk_window_set_title(w->window, title); + gtk_window_resize(w->window, width, height); + + w->vboxWidget = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); + w->vboxContainer = GTK_CONTAINER(w->vboxWidget); + w->vbox = GTK_BOX(w->vboxWidget); + + // set the vbox as the GtkWindow child + gtk_container_add(w->container, w->vboxWidget); + + if (hasMenubar) { + w->menubar = uiprivMakeMenubar(uiWindow(w)); + gtk_container_add(w->vboxContainer, w->menubar); + } + + w->childHolderWidget = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + w->childHolderContainer = GTK_CONTAINER(w->childHolderWidget); + gtk_widget_set_hexpand(w->childHolderWidget, TRUE); + gtk_widget_set_halign(w->childHolderWidget, GTK_ALIGN_FILL); + gtk_widget_set_vexpand(w->childHolderWidget, TRUE); + gtk_widget_set_valign(w->childHolderWidget, GTK_ALIGN_FILL); + gtk_container_add(w->vboxContainer, w->childHolderWidget); + + // show everything in the vbox, but not the GtkWindow itself + gtk_widget_show_all(w->vboxWidget); + + // and connect our events + g_signal_connect(w->widget, "delete-event", G_CALLBACK(onClosing), w); + g_signal_connect(w->childHolderWidget, "size-allocate", G_CALLBACK(onSizeAllocate), w); + uiWindowOnClosing(w, defaultOnClosing, NULL); + uiWindowOnContentSizeChanged(w, defaultOnPositionContentSizeChanged, NULL); + + // normally it's SetParent() that does this, but we can't call SetParent() on a uiWindow + // TODO we really need to clean this up, especially since see uiWindowDestroy() above + g_object_ref(w->widget); + + return w; +} diff --git a/dep/libui/windows/_rc2bin/build.bat b/dep/libui/windows/_rc2bin/build.bat new file mode 100644 index 0000000..5aaccf4 --- /dev/null +++ b/dep/libui/windows/_rc2bin/build.bat @@ -0,0 +1,10 @@ +@rem 2 may 2018 +@echo off + +cl /nologo /TP /GR /EHsc /MDd /Ob0 /Od /RTC1 /W4 /wd4100 /bigobj /RTC1 /RTCs /RTCu /FS -c main.cpp +if errorlevel 1 goto out +rc -foresources.res resources.rc +if errorlevel 1 goto out +link /nologo main.obj resources.res /out:main.exe /LARGEADDRESSAWARE /NOLOGO /INCREMENTAL:NO /MANIFEST:NO /debug user32.lib kernel32.lib gdi32.lib comctl32.lib uxtheme.lib msimg32.lib comdlg32.lib d2d1.lib dwrite.lib ole32.lib oleaut32.lib oleacc.lib uuid.lib + +:out diff --git a/dep/libui/windows/_rc2bin/libui.manifest b/dep/libui/windows/_rc2bin/libui.manifest new file mode 100644 index 0000000..8beb6cf --- /dev/null +++ b/dep/libui/windows/_rc2bin/libui.manifest @@ -0,0 +1,31 @@ + + + +Your application description here. + + + + + + + + + + + + + + + diff --git a/dep/libui/windows/_rc2bin/main.cpp b/dep/libui/windows/_rc2bin/main.cpp new file mode 100644 index 0000000..2143fc8 --- /dev/null +++ b/dep/libui/windows/_rc2bin/main.cpp @@ -0,0 +1,69 @@ +// 2 may 2018 +#include "winapi.hpp" +#include +#include +#include "resources.hpp" + +// TODO make sure there are no CRs in the output + +void die(const char *f, const char *constname) +{ + DWORD le; + + le = GetLastError(); + fprintf(stderr, "error calling %s for %s: %I32d\n", f, constname, le); + exit(1); +} + +void dumpResource(const char *constname, const WCHAR *name, const WCHAR *type) +{ + HRSRC hrsrc; + HGLOBAL res; + uint8_t *b, *bp; + DWORD i, n; + DWORD j; + + hrsrc = FindResourceW(NULL, name, type); + if (hrsrc == NULL) + die("FindResourceW()", constname); + n = SizeofResource(NULL, hrsrc); + if (n == 0) + die("SizeofResource()", constname); + res = LoadResource(NULL, hrsrc); + if (res == NULL) + die("LoadResource()", constname); + b = (uint8_t *) LockResource(res); + if (b == NULL) + die("LockResource()", constname); + + printf("static const uint8_t %s[] = {\n", constname); + bp = b; + j = 0; + for (i = 0; i < n; i++) { + if (j == 0) + printf("\t"); + printf("0x%02I32X,", (uint32_t) (*bp)); + bp++; + if (j == 7) { + printf("\n"); + j = 0; + } else { + printf(" "); + j++; + } + } + if (j != 0) + printf("\n"); + printf("};\n"); + printf("static_assert(ARRAYSIZE(%s) == %I32d, \"wrong size for resource %s\");\n", constname, n, constname); + printf("\n"); +} + +int main(void) +{ +#define d(c, t) dumpResource(#c, MAKEINTRESOURCEW(c), t) + d(rcTabPageDialog, RT_DIALOG); + d(rcFontDialog, RT_DIALOG); + d(rcColorDialog, RT_DIALOG); + return 0; +} diff --git a/dep/libui/windows/_rc2bin/resources.hpp b/dep/libui/windows/_rc2bin/resources.hpp new file mode 100644 index 0000000..4ae5472 --- /dev/null +++ b/dep/libui/windows/_rc2bin/resources.hpp @@ -0,0 +1,37 @@ +// 30 may 2015 + +#define rcTabPageDialog 29000 +#define rcFontDialog 29001 +#define rcColorDialog 29002 + +// TODO normalize these + +#define rcFontFamilyCombobox 1000 +#define rcFontStyleCombobox 1001 +#define rcFontSizeCombobox 1002 +#define rcFontSamplePlacement 1003 + +#define rcColorSVChooser 1100 +#define rcColorHSlider 1101 +#define rcPreview 1102 +#define rcOpacitySlider 1103 +#define rcH 1104 +#define rcS 1105 +#define rcV 1106 +#define rcRDouble 1107 +#define rcRInt 1108 +#define rcGDouble 1109 +#define rcGInt 1110 +#define rcBDouble 1111 +#define rcBInt 1112 +#define rcADouble 1113 +#define rcAInt 1114 +#define rcHex 1115 +#define rcHLabel 1116 +#define rcSLabel 1117 +#define rcVLabel 1118 +#define rcRLabel 1119 +#define rcGLabel 1120 +#define rcBLabel 1121 +#define rcALabel 1122 +#define rcHexLabel 1123 diff --git a/dep/libui/windows/_rc2bin/resources.rc b/dep/libui/windows/_rc2bin/resources.rc new file mode 100644 index 0000000..989dfc9 --- /dev/null +++ b/dep/libui/windows/_rc2bin/resources.rc @@ -0,0 +1,96 @@ +// 30 may 2015 +#include "winapi.hpp" +#include "resources.hpp" + +// this is a UTF-8 file +#pragma code_page(65001) + +// this is the Common Controls 6 manifest +// we only define it in a shared build; static builds have to include the appropriate parts of the manifest in the output executable +// LONGTERM set up the string values here +#ifndef _UI_STATIC +ISOLATIONAWARE_MANIFEST_RESOURCE_ID RT_MANIFEST "libui.manifest" +#endif + +// this is the dialog template used by tab pages; see windows/tabpage.c for details +rcTabPageDialog DIALOGEX 0, 0, 100, 100 +STYLE DS_CONTROL | WS_CHILD | WS_VISIBLE +EXSTYLE WS_EX_CONTROLPARENT +BEGIN + // nothing +END + +// this is for our custom DirectWrite-based font dialog (see fontdialog.cpp) +// this is based on the "New Font Dialog with Syslink" in Microsoft's font.dlg +// LONGTERM look at localization +// LONGTERM make it look tighter and nicer like the real one, including the actual heights of the font family and style comboboxes +rcFontDialog DIALOGEX 13, 54, 243, 200 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_3DLOOK +CAPTION "Font" +FONT 9, "Segoe UI" +BEGIN + LTEXT "&Font:", -1, 7, 7, 98, 9 + COMBOBOX rcFontFamilyCombobox, 7, 16, 98, 76, + CBS_SIMPLE | CBS_AUTOHSCROLL | CBS_DISABLENOSCROLL | + CBS_SORT | WS_VSCROLL | WS_TABSTOP | CBS_HASSTRINGS + + LTEXT "Font st&yle:", -1, 114, 7, 74, 9 + COMBOBOX rcFontStyleCombobox, 114, 16, 74, 76, + CBS_SIMPLE | CBS_AUTOHSCROLL | CBS_DISABLENOSCROLL | + WS_VSCROLL | WS_TABSTOP | CBS_HASSTRINGS + + LTEXT "&Size:", -1, 198, 7, 36, 9 + COMBOBOX rcFontSizeCombobox, 198, 16, 36, 76, + CBS_SIMPLE | CBS_AUTOHSCROLL | CBS_DISABLENOSCROLL | + CBS_SORT | WS_VSCROLL | WS_TABSTOP | CBS_HASSTRINGS + + GROUPBOX "Sample", -1, 7, 97, 227, 70, WS_GROUP + CTEXT "AaBbYyZz", rcFontSamplePlacement, 9, 106, 224, 60, SS_NOPREFIX | NOT WS_VISIBLE + + DEFPUSHBUTTON "OK", IDOK, 141, 181, 45, 14, WS_GROUP + PUSHBUTTON "Cancel", IDCANCEL, 190, 181, 45, 14, WS_GROUP +END + +rcColorDialog DIALOGEX 13, 54, 344, 209 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_3DLOOK +CAPTION "Color" +FONT 9, "Segoe UI" +BEGIN + // this size should be big enough to get at least 256x256 on font sizes >= 8 pt + CTEXT "AaBbYyZz", rcColorSVChooser, 7, 7, 195, 195, SS_NOPREFIX | SS_BLACKRECT + + // width is the suggested slider height since this is vertical + CTEXT "AaBbYyZz", rcColorHSlider, 206, 7, 15, 195, SS_NOPREFIX | SS_BLACKRECT + + LTEXT "Preview:", -1, 230, 7, 107, 9, SS_NOPREFIX + CTEXT "AaBbYyZz", rcPreview, 230, 16, 107, 20, SS_NOPREFIX | SS_BLACKRECT + + LTEXT "Opacity:", -1, 230, 45, 107, 9, SS_NOPREFIX + CTEXT "AaBbYyZz", rcOpacitySlider, 230, 54, 107, 15, SS_NOPREFIX | SS_BLACKRECT + + LTEXT "&H:", rcHLabel, 230, 81, 8, 8 + EDITTEXT rcH, 238, 78, 30, 14, ES_LEFT | ES_AUTOHSCROLL | WS_TABSTOP, WS_EX_CLIENTEDGE + LTEXT "&S:", rcSLabel, 230, 95, 8, 8 + EDITTEXT rcS, 238, 92, 30, 14, ES_LEFT | ES_AUTOHSCROLL | WS_TABSTOP, WS_EX_CLIENTEDGE + LTEXT "&V:", rcVLabel, 230, 109, 8, 8 + EDITTEXT rcV, 238, 106, 30, 14, ES_LEFT | ES_AUTOHSCROLL | WS_TABSTOP, WS_EX_CLIENTEDGE + + LTEXT "&R:", rcRLabel, 277, 81, 8, 8 + EDITTEXT rcRDouble, 285, 78, 30, 14, ES_LEFT | ES_AUTOHSCROLL | WS_TABSTOP, WS_EX_CLIENTEDGE + EDITTEXT rcRInt, 315, 78, 20, 14, ES_LEFT | ES_AUTOHSCROLL | ES_NUMBER | WS_TABSTOP, WS_EX_CLIENTEDGE + LTEXT "&G:", rcGLabel, 277, 95, 8, 8 + EDITTEXT rcGDouble, 285, 92, 30, 14, ES_LEFT | ES_AUTOHSCROLL | WS_TABSTOP, WS_EX_CLIENTEDGE + EDITTEXT rcGInt, 315, 92, 20, 14, ES_LEFT | ES_AUTOHSCROLL | ES_NUMBER | WS_TABSTOP, WS_EX_CLIENTEDGE + LTEXT "&B:", rcBLabel, 277, 109, 8, 8 + EDITTEXT rcBDouble, 285, 106, 30, 14, ES_LEFT | ES_AUTOHSCROLL | WS_TABSTOP, WS_EX_CLIENTEDGE + EDITTEXT rcBInt, 315, 106, 20, 14, ES_LEFT | ES_AUTOHSCROLL | ES_NUMBER | WS_TABSTOP, WS_EX_CLIENTEDGE + LTEXT "&A:", rcALabel, 277, 123, 8, 8 + EDITTEXT rcADouble, 285, 120, 30, 14, ES_LEFT | ES_AUTOHSCROLL | WS_TABSTOP, WS_EX_CLIENTEDGE + EDITTEXT rcAInt, 315, 120, 20, 14, ES_LEFT | ES_AUTOHSCROLL | ES_NUMBER | WS_TABSTOP, WS_EX_CLIENTEDGE + + LTEXT "He&x:", rcHexLabel, 269, 146, 16, 8 + EDITTEXT rcHex, 285, 143, 50, 14, ES_LEFT | ES_AUTOHSCROLL | WS_TABSTOP, WS_EX_CLIENTEDGE + + DEFPUSHBUTTON "OK", IDOK, 243, 188, 45, 14, WS_GROUP + PUSHBUTTON "Cancel", IDCANCEL, 292, 188, 45, 14, WS_GROUP +END diff --git a/dep/libui/windows/_rc2bin/winapi.hpp b/dep/libui/windows/_rc2bin/winapi.hpp new file mode 100644 index 0000000..f545880 --- /dev/null +++ b/dep/libui/windows/_rc2bin/winapi.hpp @@ -0,0 +1,60 @@ +// 31 may 2015 +#define UNICODE +#define _UNICODE +#define STRICT +#define STRICT_TYPED_ITEMIDS + +// see https://github.com/golang/go/issues/9916#issuecomment-74812211 +// TODO get rid of this +#define INITGUID + +// for the manifest +#ifndef _UI_STATIC +#define ISOLATION_AWARE_ENABLED 1 +#endif + +// get Windows version right; right now Windows Vista +// unless otherwise stated, all values from Microsoft's sdkddkver.h +// TODO is all of this necessary? how is NTDDI_VERSION used? +// TODO platform update sp2 +#define WINVER 0x0600 /* from Microsoft's winnls.h */ +#define _WIN32_WINNT 0x0600 +#define _WIN32_WINDOWS 0x0600 /* from Microsoft's pdh.h */ +#define _WIN32_IE 0x0700 +#define NTDDI_VERSION 0x06000000 + +// The MinGW-w64 header has an unverified IDWriteTypography definition. +// TODO I can confirm this myself, but I don't know how long it will take for them to note my adjustments... Either way, I have to confirm this myself. +// TODO change the check from _MSC_VER to a MinGW-w64-specific check +// TODO keep track of what else is guarded by this +#ifndef _MSC_VER +#define __MINGW_USE_BROKEN_INTERFACE +#endif + +#include + +// Microsoft's resource compiler will segfault if we feed it headers it was not designed to handle +#ifndef RC_INVOKED +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#endif diff --git a/dep/libui/windows/_uipriv_migrate.hpp b/dep/libui/windows/_uipriv_migrate.hpp new file mode 100644 index 0000000..96a6708 --- /dev/null +++ b/dep/libui/windows/_uipriv_migrate.hpp @@ -0,0 +1,14 @@ + +// menu.c +extern HMENU makeMenubar(void); +extern const uiMenuItem *menuIDToItem(UINT_PTR); +extern void runMenuEvent(WORD, uiWindow *); +extern void freeMenubar(HMENU); +extern void uninitMenus(void); + +// draw.c +extern HRESULT initDraw(void); +extern void uninitDraw(void); +extern ID2D1HwndRenderTarget *makeHWNDRenderTarget(HWND hwnd); +extern uiDrawContext *newContext(ID2D1RenderTarget *); +extern void freeContext(uiDrawContext *); diff --git a/dep/libui/windows/alloc.cpp b/dep/libui/windows/alloc.cpp new file mode 100644 index 0000000..321cca0 --- /dev/null +++ b/dep/libui/windows/alloc.cpp @@ -0,0 +1,64 @@ +// 4 december 2014 +#include "uipriv_windows.hpp" + +typedef std::vector byteArray; + +static std::map heap; +static std::map types; + +void initAlloc(void) +{ + // do nothing +} + +void uninitAlloc(void) +{ + std::ostringstream oss; + std::string ossstr; // keep alive, just to be safe + + if (heap.size() == 0) + return; + for (const auto &alloc : heap) + // note the void * cast; otherwise it'll be treated as a string + oss << (void *) (alloc.first) << " " << types[alloc.second] << "\n"; + ossstr = oss.str(); + uiprivUserBug("Some data was leaked; either you left a uiControl lying around or there's a bug in libui itself. Leaked data:\n%s", ossstr.c_str()); +} + +#define rawBytes(pa) (&((*pa)[0])) + +void *uiprivAlloc(size_t size, const char *type) +{ + byteArray *out; + + out = new byteArray(size, 0); + heap[rawBytes(out)] = out; + types[out] = type; + return rawBytes(out); +} + +void *uiprivRealloc(void *_p, size_t size, const char *type) +{ + uint8_t *p = (uint8_t *) _p; + byteArray *arr; + + if (p == NULL) + return uiprivAlloc(size, type); + arr = heap[p]; + // TODO does this fill in? + arr->resize(size, 0); + heap.erase(p); + heap[rawBytes(arr)] = arr; + return rawBytes(arr); +} + +void uiprivFree(void *_p) +{ + uint8_t *p = (uint8_t *) _p; + + if (p == NULL) + uiprivImplBug("attempt to uiprivFree(NULL)"); + types.erase(heap[p]); + delete heap[p]; + heap.erase(p); +} diff --git a/dep/libui/windows/area.cpp b/dep/libui/windows/area.cpp new file mode 100644 index 0000000..0042fcc --- /dev/null +++ b/dep/libui/windows/area.cpp @@ -0,0 +1,206 @@ +// 8 september 2015 +#include "uipriv_windows.hpp" +#include "area.hpp" + +// TODO handle WM_DESTROY/WM_NCDESTROY +// TODO same for other Direct2D stuff +static LRESULT CALLBACK areaWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + uiArea *a; + CREATESTRUCTW *cs = (CREATESTRUCTW *) lParam; + RECT client; + WINDOWPOS *wp = (WINDOWPOS *) lParam; + LRESULT lResult; + + a = (uiArea *) GetWindowLongPtrW(hwnd, GWLP_USERDATA); + if (a == NULL) { + if (uMsg == WM_CREATE) { + a = (uiArea *) (cs->lpCreateParams); + // assign a->hwnd here so we can use it immediately + a->hwnd = hwnd; + SetWindowLongPtrW(hwnd, GWLP_USERDATA, (LONG_PTR) a); + } + // fall through to DefWindowProcW() anyway + return DefWindowProcW(hwnd, uMsg, wParam, lParam); + } + + // always recreate the render target if necessary + if (a->rt == NULL) + a->rt = makeHWNDRenderTarget(a->hwnd); + + if (areaDoDraw(a, uMsg, wParam, lParam, &lResult) != FALSE) + return lResult; + + if (uMsg == WM_WINDOWPOSCHANGED) { + if ((wp->flags & SWP_NOSIZE) != 0) + return DefWindowProcW(hwnd, uMsg, wParam, lParam); + uiWindowsEnsureGetClientRect(a->hwnd, &client); + areaDrawOnResize(a, &client); + areaScrollOnResize(a, &client); + return 0; + } + + if (areaDoScroll(a, uMsg, wParam, lParam, &lResult) != FALSE) + return lResult; + if (areaDoEvents(a, uMsg, wParam, lParam, &lResult) != FALSE) + return lResult; + + // nothing done + return DefWindowProc(hwnd, uMsg, wParam, lParam); +} + +// control implementation + +uiWindowsControlAllDefaults(uiArea) + +static void uiAreaMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + // TODO + *width = 0; + *height = 0; +} + +ATOM registerAreaClass(HICON hDefaultIcon, HCURSOR hDefaultCursor) +{ + WNDCLASSW wc; + + ZeroMemory(&wc, sizeof (WNDCLASSW)); + wc.lpszClassName = areaClass; + wc.lpfnWndProc = areaWndProc; + wc.hInstance = hInstance; + wc.hIcon = hDefaultIcon; + wc.hCursor = hDefaultCursor; + wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1); + // this is just to be safe; see the InvalidateRect() call in the WM_WINDOWPOSCHANGED handler for more details + wc.style = CS_HREDRAW | CS_VREDRAW; + return RegisterClassW(&wc); +} + +void unregisterArea(void) +{ + if (UnregisterClassW(areaClass, hInstance) == 0) + logLastError(L"error unregistering uiArea window class"); +} + +void uiAreaSetSize(uiArea *a, int width, int height) +{ + a->scrollWidth = width; + a->scrollHeight = height; + areaUpdateScroll(a); +} + +void uiAreaQueueRedrawAll(uiArea *a) +{ + // don't erase the background; we do that ourselves in doPaint() + invalidateRect(a->hwnd, NULL, FALSE); +} + +void uiAreaScrollTo(uiArea *a, double x, double y, double width, double height) +{ + // TODO +} + +void uiAreaBeginUserWindowMove(uiArea *a) +{ + HWND toplevel; + + // TODO restrict execution + ReleaseCapture(); // TODO use properly and reset internal data structures + toplevel = parentToplevel(a->hwnd); + if (toplevel == NULL) { + // TODO + return; + } + // see http://stackoverflow.com/questions/40249940/how-do-i-initiate-a-user-mouse-driven-move-or-resize-for-custom-window-borders-o#40250654 + SendMessageW(toplevel, WM_SYSCOMMAND, + SC_MOVE | 2, 0); +} + +void uiAreaBeginUserWindowResize(uiArea *a, uiWindowResizeEdge edge) +{ + HWND toplevel; + WPARAM wParam; + + // TODO restrict execution + ReleaseCapture(); // TODO use properly and reset internal data structures + toplevel = parentToplevel(a->hwnd); + if (toplevel == NULL) { + // TODO + return; + } + // see http://stackoverflow.com/questions/40249940/how-do-i-initiate-a-user-mouse-driven-move-or-resize-for-custom-window-borders-o#40250654 + wParam = SC_SIZE; + switch (edge) { + case uiWindowResizeEdgeLeft: + wParam |= 1; + break; + case uiWindowResizeEdgeTop: + wParam |= 3; + break; + case uiWindowResizeEdgeRight: + wParam |= 2; + break; + case uiWindowResizeEdgeBottom: + wParam |= 6; + break; + case uiWindowResizeEdgeTopLeft: + wParam |= 4; + break; + case uiWindowResizeEdgeTopRight: + wParam |= 5; + break; + case uiWindowResizeEdgeBottomLeft: + wParam |= 7; + break; + case uiWindowResizeEdgeBottomRight: + wParam |= 8; + break; + } + SendMessageW(toplevel, WM_SYSCOMMAND, + wParam, 0); +} + +uiArea *uiNewArea(uiAreaHandler *ah) +{ + uiArea *a; + + uiWindowsNewControl(uiArea, a); + + a->ah = ah; + a->scrolling = FALSE; + uiprivClickCounterReset(&(a->cc)); + + // a->hwnd is assigned in areaWndProc() + uiWindowsEnsureCreateControlHWND(0, + areaClass, L"", + 0, + hInstance, a, + FALSE); + + return a; +} + +uiArea *uiNewScrollingArea(uiAreaHandler *ah, int width, int height) +{ + uiArea *a; + + uiWindowsNewControl(uiArea, a); + + a->ah = ah; + a->scrolling = TRUE; + a->scrollWidth = width; + a->scrollHeight = height; + uiprivClickCounterReset(&(a->cc)); + + // a->hwnd is assigned in areaWndProc() + uiWindowsEnsureCreateControlHWND(0, + areaClass, L"", + WS_HSCROLL | WS_VSCROLL, + hInstance, a, + FALSE); + + // set initial scrolling parameters + areaUpdateScroll(a); + + return a; +} diff --git a/dep/libui/windows/area.hpp b/dep/libui/windows/area.hpp new file mode 100644 index 0000000..dfc2bc5 --- /dev/null +++ b/dep/libui/windows/area.hpp @@ -0,0 +1,45 @@ +// 18 december 2015 + +// TODOs +// - things look very wrong on initial draw +// - initial scrolling is not set properly +// - should background be inherited from parent control? + +struct uiArea { + uiWindowsControl c; + HWND hwnd; + uiAreaHandler *ah; + + BOOL scrolling; + int scrollWidth; + int scrollHeight; + int hscrollpos; + int vscrollpos; + int hwheelCarry; + int vwheelCarry; + + uiprivClickCounter cc; + BOOL capturing; + + BOOL inside; + BOOL tracking; + + ID2D1HwndRenderTarget *rt; +}; + +// areadraw.cpp +extern BOOL areaDoDraw(uiArea *a, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *lResult); +extern void areaDrawOnResize(uiArea *, RECT *); + +// areascroll.cpp +extern BOOL areaDoScroll(uiArea *a, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *lResult); +extern void areaScrollOnResize(uiArea *, RECT *); +extern void areaUpdateScroll(uiArea *a); + +// areaevents.cpp +extern BOOL areaDoEvents(uiArea *a, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *lResult); + +// areautil.cpp +extern void loadAreaSize(uiArea *a, ID2D1RenderTarget *rt, double *width, double *height); +extern void pixelsToDIP(uiArea *a, double *x, double *y); +extern void dipToPixels(uiArea *a, double *x, double *y); diff --git a/dep/libui/windows/areadraw.cpp b/dep/libui/windows/areadraw.cpp new file mode 100644 index 0000000..7b3dc69 --- /dev/null +++ b/dep/libui/windows/areadraw.cpp @@ -0,0 +1,137 @@ +// 8 september 2015 +#include "uipriv_windows.hpp" +#include "area.hpp" + +static HRESULT doPaint(uiArea *a, ID2D1RenderTarget *rt, RECT *clip) +{ + uiAreaHandler *ah = a->ah; + uiAreaDrawParams dp; + COLORREF bgcolorref; + D2D1_COLOR_F bgcolor; + D2D1_MATRIX_3X2_F scrollTransform; + + // no need to save or restore the graphics state to reset transformations; it's handled by resetTarget() in draw.c, called during the following + dp.Context = newContext(rt); + + loadAreaSize(a, rt, &(dp.AreaWidth), &(dp.AreaHeight)); + + dp.ClipX = clip->left; + dp.ClipY = clip->top; + dp.ClipWidth = clip->right - clip->left; + dp.ClipHeight = clip->bottom - clip->top; + if (a->scrolling) { + dp.ClipX += a->hscrollpos; + dp.ClipY += a->vscrollpos; + } + + rt->BeginDraw(); + + if (a->scrolling) { + ZeroMemory(&scrollTransform, sizeof (D2D1_MATRIX_3X2_F)); + scrollTransform._11 = 1; + scrollTransform._22 = 1; + // negative because we want nonzero scroll positions to move the drawing area up/left + scrollTransform._31 = -a->hscrollpos; + scrollTransform._32 = -a->vscrollpos; + rt->SetTransform(&scrollTransform); + } + + // TODO push axis aligned clip + + // TODO only clear the clip area + // TODO clear with actual background brush + bgcolorref = GetSysColor(COLOR_BTNFACE); + bgcolor.r = ((float) GetRValue(bgcolorref)) / 255.0; + // due to utter apathy on Microsoft's part, GetGValue() does not work with MSVC's Run-Time Error Checks + // it has not worked since 2008 and they have *never* fixed it + // TODO now that -RTCc has just been deprecated entirely, should we switch back? + bgcolor.g = ((float) ((BYTE) ((bgcolorref & 0xFF00) >> 8))) / 255.0; + bgcolor.b = ((float) GetBValue(bgcolorref)) / 255.0; + bgcolor.a = 1.0; + rt->Clear(&bgcolor); + + (*(ah->Draw))(ah, a, &dp); + + freeContext(dp.Context); + + // TODO pop axis aligned clip + + return rt->EndDraw(NULL, NULL); +} + +static void onWM_PAINT(uiArea *a) +{ + RECT clip; + HRESULT hr; + + // do not clear the update rect; we do that ourselves in doPaint() + if (GetUpdateRect(a->hwnd, &clip, FALSE) == 0) { + // set a zero clip rect just in case GetUpdateRect() didn't change clip + clip.left = 0; + clip.top = 0; + clip.right = 0; + clip.bottom = 0; + } + hr = doPaint(a, a->rt, &clip); + switch (hr) { + case S_OK: + if (ValidateRect(a->hwnd, NULL) == 0) + logLastError(L"error validating rect"); + break; + case D2DERR_RECREATE_TARGET: + // DON'T validate the rect + // instead, simply drop the render target + // we'll get another WM_PAINT and make the render target again + // TODO would this require us to invalidate the entire client area? + a->rt->Release();; + a->rt = NULL; + break; + default: + logHRESULT(L"error painting", hr); + } +} + +static void onWM_PRINTCLIENT(uiArea *a, HDC dc) +{ + ID2D1DCRenderTarget *rt; + RECT client; + HRESULT hr; + + uiWindowsEnsureGetClientRect(a->hwnd, &client); + rt = makeHDCRenderTarget(dc, &client); + hr = doPaint(a, rt, &client); + if (hr != S_OK) + logHRESULT(L"error printing uiArea client area", hr); + rt->Release(); +} + +BOOL areaDoDraw(uiArea *a, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *lResult) +{ + switch (uMsg) { + case WM_PAINT: + onWM_PAINT(a); + *lResult = 0; + return TRUE; + case WM_PRINTCLIENT: + onWM_PRINTCLIENT(a, (HDC) wParam); + *lResult = 0; + return TRUE; + } + return FALSE; +} + +// TODO only if the render target wasn't just created? +void areaDrawOnResize(uiArea *a, RECT *newClient) +{ + D2D1_SIZE_U size; + + size.width = newClient->right - newClient->left; + size.height = newClient->bottom - newClient->top; + // don't track the error; we'll get that in EndDraw() + // see https://msdn.microsoft.com/en-us/library/windows/desktop/dd370994%28v=vs.85%29.aspx + a->rt->Resize(&size); + + // according to Rick Brewster, we must always redraw the entire client area after calling ID2D1RenderTarget::Resize() (see http://stackoverflow.com/a/33222983/3408572) + // we used to have a uiAreaHandler.RedrawOnResize() method to decide this; now you know why we don't anymore + invalidateRect(a->hwnd, NULL, TRUE); +} diff --git a/dep/libui/windows/areaevents.cpp b/dep/libui/windows/areaevents.cpp new file mode 100644 index 0000000..c7014ec --- /dev/null +++ b/dep/libui/windows/areaevents.cpp @@ -0,0 +1,423 @@ +// 8 september 2015 +#include "uipriv_windows.hpp" +#include "area.hpp" + +// TODO https://github.com/Microsoft/Windows-classic-samples/blob/master/Samples/Win7Samples/multimedia/DirectWrite/PadWrite/TextEditor.cpp notes on explicit RTL handling under MirrorXCoordinate(); also in areadraw.cpp too? + +static uiModifiers getModifiers(void) +{ + uiModifiers m = 0; + + if ((GetKeyState(VK_CONTROL) & 0x80) != 0) + m |= uiModifierCtrl; + if ((GetKeyState(VK_MENU) & 0x80) != 0) + m |= uiModifierAlt; + if ((GetKeyState(VK_SHIFT) & 0x80) != 0) + m |= uiModifierShift; + if ((GetKeyState(VK_LWIN) & 0x80) != 0) + m |= uiModifierSuper; + if ((GetKeyState(VK_RWIN) & 0x80) != 0) + m |= uiModifierSuper; + return m; +} + +/* +Windows doesn't natively support mouse crossing events. + +TrackMouseEvent() (and its comctl32.dll wrapper _TrackMouseEvent()) both allow for a window to receive the WM_MOUSELEAVE message when the mouse leaves the client area. There's no equivalent WM_MOUSEENTER because it can be simulated (https://blogs.msdn.microsoft.com/oldnewthing/20031013-00/?p=42193). + +Unfortunately, WM_MOUSELEAVE does not get generated while the mouse is captured. We need to capture for drag behavior to work properly, so this isn't going to mix well. + +So what we do: +- on WM_MOUSEMOVE, if we don't have the capture, start tracking + - this will handle the case of the capture being released while still in the area +- on WM_MOUSELEAVE, mark that we are no longer tracking + - Windows has already done the work of that for us; it's just a flag we use for the next part +- when starting capture, stop tracking if we are tracking +- if capturing, manually check if the pointer is in the client rect on each area event +*/ +static void track(uiArea *a, BOOL tracking) +{ + TRACKMOUSEEVENT tm; + + // do nothing if there's no change + if (a->tracking && tracking) + return; + if (!a->tracking && !tracking) + return; + + a->tracking = tracking; + ZeroMemory(&tm, sizeof (TRACKMOUSEEVENT)); + tm.cbSize = sizeof (TRACKMOUSEEVENT); + tm.dwFlags = TME_LEAVE; + if (!a->tracking) + tm.dwFlags |= TME_CANCEL; + tm.hwndTrack = a->hwnd; + if (_TrackMouseEvent(&tm) == 0) + logLastError(L"error setting up mouse tracking"); +} + +static void capture(uiArea *a, BOOL capturing) +{ + // do nothing if there's no change + if (a->capturing && capturing) + return; + if (!a->capturing && !capturing) + return; + + // change flag first as ReleaseCapture() sends WM_CAPTURECHANGED + a->capturing = capturing; + if (a->capturing) { + track(a, FALSE); + SetCapture(a->hwnd); + } else + if (ReleaseCapture() == 0) + logLastError(L"error releasing capture on drag"); +} + +static void areaMouseEvent(uiArea *a, int down, int up, WPARAM wParam, LPARAM lParam) +{ + uiAreaMouseEvent me; + int button; + POINT clientpt; + RECT client; + BOOL inClient; + double xpix, ypix; + + if (a->capturing) { + clientpt.x = GET_X_LPARAM(lParam); + clientpt.y = GET_Y_LPARAM(lParam); + uiWindowsEnsureGetClientRect(a->hwnd, &client); + inClient = PtInRect(&client, clientpt); + if (inClient && !a->inside) { + a->inside = TRUE; + (*(a->ah->MouseCrossed))(a->ah, a, 0); + uiprivClickCounterReset(&(a->cc)); + } else if (!inClient && a->inside) { + a->inside = FALSE; + (*(a->ah->MouseCrossed))(a->ah, a, 1); + uiprivClickCounterReset(&(a->cc)); + } + } + + xpix = (double) GET_X_LPARAM(lParam); + ypix = (double) GET_Y_LPARAM(lParam); + // these are in pixels; we need points + pixelsToDIP(a, &xpix, &ypix); + me.X = xpix; + me.Y = ypix; + if (a->scrolling) { + me.X += a->hscrollpos; + me.Y += a->vscrollpos; + } + + loadAreaSize(a, NULL, &(me.AreaWidth), &(me.AreaHeight)); + + me.Down = down; + me.Up = up; + me.Count = 0; + if (me.Down != 0) + // GetMessageTime() returns LONG and GetDoubleClckTime() returns UINT, which are int32 and uint32, respectively, but we don't need to worry about the signedness because for the same bit widths and two's complement arithmetic, s1-s2 == u1-u2 if bits(s1)==bits(s2) and bits(u1)==bits(u2) (and Windows requires two's complement: http://blogs.msdn.com/b/oldnewthing/archive/2005/05/27/422551.aspx) + // signedness isn't much of an issue for these calls anyway because http://stackoverflow.com/questions/24022225/what-are-the-sign-extension-rules-for-calling-windows-api-functions-stdcall-t and that we're only using unsigned values (think back to how you (didn't) handle signedness in assembly language) AND because of the above AND because the statistics below (time interval and width/height) really don't make sense if negative + // GetSystemMetrics() returns int, which is int32 + me.Count = uiprivClickCounterClick(&(a->cc), me.Down, + me.X, me.Y, + GetMessageTime(), GetDoubleClickTime(), + GetSystemMetrics(SM_CXDOUBLECLK) / 2, + GetSystemMetrics(SM_CYDOUBLECLK) / 2); + + // though wparam will contain control and shift state, let's just one function to get modifiers for both keyboard and mouse events; it'll work the same anyway since we have to do this for alt and windows key (super) + me.Modifiers = getModifiers(); + + button = me.Down; + if (button == 0) + button = me.Up; + me.Held1To64 = 0; + if (button != 1 && (wParam & MK_LBUTTON) != 0) + me.Held1To64 |= 1 << 0; + if (button != 2 && (wParam & MK_MBUTTON) != 0) + me.Held1To64 |= 1 << 1; + if (button != 3 && (wParam & MK_RBUTTON) != 0) + me.Held1To64 |= 1 << 2; + if (button != 4 && (wParam & MK_XBUTTON1) != 0) + me.Held1To64 |= 1 << 3; + if (button != 5 && (wParam & MK_XBUTTON2) != 0) + me.Held1To64 |= 1 << 4; + + // on Windows, we have to capture on drag ourselves + if (me.Down != 0) + capture(a, TRUE); + // only release capture when all buttons released + if (me.Up != 0 && me.Held1To64 == 0) + capture(a, FALSE); + + (*(a->ah->MouseEvent))(a->ah, a, &me); +} + +// TODO genericize this so it can be called above +static void onMouseEntered(uiArea *a) +{ + if (a->inside) + return; + if (a->capturing) // we handle mouse crossing in areaMouseEvent() + return; + track(a, TRUE); + (*(a->ah->MouseCrossed))(a->ah, a, 0); + // TODO figure out why we did this to begin with; either we do it on both GTK+ and Windows or not at all + uiprivClickCounterReset(&(a->cc)); +} + +// TODO genericize it so that it can be called above +static void onMouseLeft(uiArea *a) +{ + a->tracking = FALSE; + a->inside = FALSE; + (*(a->ah->MouseCrossed))(a->ah, a, 1); + // TODO figure out why we did this to begin with; either we do it on both GTK+ and Windows or not at all + uiprivClickCounterReset(&(a->cc)); +} + +// we use VK_SNAPSHOT as a sentinel because libui will never support the print screen key; that key belongs to the user +struct extkeymap { + WPARAM vk; + uiExtKey extkey; +}; + +// all mappings come from GLFW - https://github.com/glfw/glfw/blob/master/src/win32_window.c#L152 +static const struct extkeymap numpadExtKeys[] = { + { VK_HOME, uiExtKeyN7 }, + { VK_UP, uiExtKeyN8 }, + { VK_PRIOR, uiExtKeyN9 }, + { VK_LEFT, uiExtKeyN4 }, + { VK_CLEAR, uiExtKeyN5 }, + { VK_RIGHT, uiExtKeyN6 }, + { VK_END, uiExtKeyN1 }, + { VK_DOWN, uiExtKeyN2 }, + { VK_NEXT, uiExtKeyN3 }, + { VK_INSERT, uiExtKeyN0 }, + { VK_DELETE, uiExtKeyNDot }, + { VK_SNAPSHOT, 0 }, +}; + +static const struct extkeymap extKeys[] = { + { VK_ESCAPE, uiExtKeyEscape }, + { VK_INSERT, uiExtKeyInsert }, + { VK_DELETE, uiExtKeyDelete }, + { VK_HOME, uiExtKeyHome }, + { VK_END, uiExtKeyEnd }, + { VK_PRIOR, uiExtKeyPageUp }, + { VK_NEXT, uiExtKeyPageDown }, + { VK_UP, uiExtKeyUp }, + { VK_DOWN, uiExtKeyDown }, + { VK_LEFT, uiExtKeyLeft }, + { VK_RIGHT, uiExtKeyRight }, + { VK_F1, uiExtKeyF1 }, + { VK_F2, uiExtKeyF2 }, + { VK_F3, uiExtKeyF3 }, + { VK_F4, uiExtKeyF4 }, + { VK_F5, uiExtKeyF5 }, + { VK_F6, uiExtKeyF6 }, + { VK_F7, uiExtKeyF7 }, + { VK_F8, uiExtKeyF8 }, + { VK_F9, uiExtKeyF9 }, + { VK_F10, uiExtKeyF10 }, + { VK_F11, uiExtKeyF11 }, + { VK_F12, uiExtKeyF12 }, + // numpad numeric keys and . are handled in common/areaevents.c + // numpad enter is handled in code below + { VK_ADD, uiExtKeyNAdd }, + { VK_SUBTRACT, uiExtKeyNSubtract }, + { VK_MULTIPLY, uiExtKeyNMultiply }, + { VK_DIVIDE, uiExtKeyNDivide }, + { VK_SNAPSHOT, 0 }, +}; + +static const struct { + WPARAM vk; + uiModifiers mod; +} modKeys[] = { + // even if the separate left/right aren't necessary, have them here anyway, just to be safe + { VK_CONTROL, uiModifierCtrl }, + { VK_LCONTROL, uiModifierCtrl }, + { VK_RCONTROL, uiModifierCtrl }, + { VK_MENU, uiModifierAlt }, + { VK_LMENU, uiModifierAlt }, + { VK_RMENU, uiModifierAlt }, + { VK_SHIFT, uiModifierShift }, + { VK_LSHIFT, uiModifierShift }, + { VK_RSHIFT, uiModifierShift }, + // there's no combined Windows key virtual-key code as there is with the others + { VK_LWIN, uiModifierSuper }, + { VK_RWIN, uiModifierSuper }, + { VK_SNAPSHOT, 0 }, +}; + +static int areaKeyEvent(uiArea *a, int up, WPARAM wParam, LPARAM lParam) +{ + uiAreaKeyEvent ke; + int righthand; + int i; + + ke.Key = 0; + ke.ExtKey = 0; + ke.Modifier = 0; + + ke.Modifiers = getModifiers(); + + ke.Up = up; + + // the numeric keypad keys when Num Lock is off are considered left-hand keys as the separate navigation buttons were added later + // the numeric keypad Enter, however, is a right-hand key because it has the same virtual-key code as the typewriter Enter + righthand = (lParam & 0x01000000) != 0; + if (righthand) { + if (wParam == VK_RETURN) { + ke.ExtKey = uiExtKeyNEnter; + goto keyFound; + } + } else + // this is special handling for numpad keys to ignore the state of Num Lock and Shift; see http://blogs.msdn.com/b/oldnewthing/archive/2004/09/06/226045.aspx and https://github.com/glfw/glfw/blob/master/src/win32_window.c#L152 + for (i = 0; numpadExtKeys[i].vk != VK_SNAPSHOT; i++) + if (numpadExtKeys[i].vk == wParam) { + ke.ExtKey = numpadExtKeys[i].extkey; + goto keyFound; + } + + // okay, those above cases didn't match anything + // first try the extended keys + for (i = 0; extKeys[i].vk != VK_SNAPSHOT; i++) + if (extKeys[i].vk == wParam) { + ke.ExtKey = extKeys[i].extkey; + goto keyFound; + } + + // then try modifier keys + for (i = 0; modKeys[i].vk != VK_SNAPSHOT; i++) + if (modKeys[i].vk == wParam) { + ke.Modifier = modKeys[i].mod; + // and don't include the key in Modifiers + ke.Modifiers &= ~ke.Modifier; + goto keyFound; + } + + // and finally everything else + if (uiprivFromScancode((lParam >> 16) & 0xFF, &ke)) + goto keyFound; + + // not a supported key, assume unhandled + // TODO the original code only did this if ke.Modifiers == 0 - why? + return 0; + +keyFound: + return (*(a->ah->KeyEvent))(a->ah, a, &ke); +} + +// We don't handle the standard Windows keyboard messages directly, to avoid both the dialog manager and TranslateMessage(). +// Instead, we set up a message filter and do things there. +// That stuff is later in this file. +enum { + // start at 0x40 to avoid clobbering dialog messages + msgAreaKeyDown = WM_USER + 0x40, + msgAreaKeyUp, +}; + +BOOL areaDoEvents(uiArea *a, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *lResult) +{ + switch (uMsg) { + case WM_ACTIVATE: + // don't keep the double-click timer running if the user switched programs in between clicks + uiprivClickCounterReset(&(a->cc)); + *lResult = 0; + return TRUE; + case WM_MOUSEMOVE: + onMouseEntered(a); + areaMouseEvent(a, 0, 0, wParam, lParam); + *lResult = 0; + return TRUE; + case WM_MOUSELEAVE: + onMouseLeft(a); + *lResult = 0; + return TRUE; + case WM_LBUTTONDOWN: + SetFocus(a->hwnd); + areaMouseEvent(a, 1, 0, wParam, lParam); + *lResult = 0; + return TRUE; + case WM_LBUTTONUP: + areaMouseEvent(a, 0, 1, wParam, lParam); + *lResult = 0; + return TRUE; + case WM_MBUTTONDOWN: + SetFocus(a->hwnd); + areaMouseEvent(a, 2, 0, wParam, lParam); + *lResult = 0; + return TRUE; + case WM_MBUTTONUP: + areaMouseEvent(a, 0, 2, wParam, lParam); + *lResult = 0; + return TRUE; + case WM_RBUTTONDOWN: + SetFocus(a->hwnd); + areaMouseEvent(a, 3, 0, wParam, lParam); + *lResult = 0; + return TRUE; + case WM_RBUTTONUP: + areaMouseEvent(a, 0, 3, wParam, lParam); + *lResult = 0; + return TRUE; + case WM_XBUTTONDOWN: + SetFocus(a->hwnd); + // values start at 1; we want them to start at 4 + areaMouseEvent(a, + GET_XBUTTON_WPARAM(wParam) + 3, 0, + GET_KEYSTATE_WPARAM(wParam), lParam); + *lResult = TRUE; // XBUTTON messages are different! + return TRUE; + case WM_XBUTTONUP: + areaMouseEvent(a, + 0, GET_XBUTTON_WPARAM(wParam) + 3, + GET_KEYSTATE_WPARAM(wParam), lParam); + *lResult = TRUE; // XBUTTON messages are different! + return TRUE; + case WM_CAPTURECHANGED: + if (a->capturing) { + a->capturing = FALSE; + (*(a->ah->DragBroken))(a->ah, a); + } + *lResult = 0; + return TRUE; + case msgAreaKeyDown: + *lResult = (LRESULT) areaKeyEvent(a, 0, wParam, lParam); + return TRUE; + case msgAreaKeyUp: + *lResult = (LRESULT) areaKeyEvent(a, 1, wParam, lParam); + return TRUE; + } + return FALSE; +} + +// TODO affect visibility properly +// TODO what did this mean +BOOL areaFilter(MSG *msg) +{ + LRESULT handled; + + // is the recipient an area? + if (msg->hwnd == NULL) // this can happen; for example, WM_TIMER + return FALSE; + if (windowClassOf(msg->hwnd, areaClass, NULL) != 0) + return FALSE; // nope + + handled = 0; + switch (msg->message) { + case WM_KEYDOWN: + case WM_SYSKEYDOWN: + handled = SendMessageW(msg->hwnd, msgAreaKeyDown, msg->wParam, msg->lParam); + break; + case WM_KEYUP: + case WM_SYSKEYUP: + handled = SendMessageW(msg->hwnd, msgAreaKeyUp, msg->wParam, msg->lParam); + break; + // otherwise handled remains 0, as we didn't handle this + } + return (BOOL) handled; +} diff --git a/dep/libui/windows/areascroll.cpp b/dep/libui/windows/areascroll.cpp new file mode 100644 index 0000000..f18d0ad --- /dev/null +++ b/dep/libui/windows/areascroll.cpp @@ -0,0 +1,247 @@ +// 8 september 2015 +#include "uipriv_windows.hpp" +#include "area.hpp" + +// TODO +// - move from pixels to points somehow +// - add a function to offset points and rects by scrolling amounts; call it from doPaint() in areadraw.c +// - recalculate scrolling after: +// - creation? +// - resize? +// - recreating the render target? (after moving to points) +// - error if these are called without scrollbars? + +struct scrollParams { + int *pos; + int pagesize; + int length; + int *wheelCarry; + UINT wheelSPIAction; +}; + +static void scrollto(uiArea *a, int which, struct scrollParams *p, int pos) +{ + SCROLLINFO si; + + // note that the pos < 0 check is /after/ the p->length - p->pagesize check + // it used to be /before/; this was actually a bug in Raymond Chen's original algorithm: if there are fewer than a page's worth of items, p->length - p->pagesize will be negative and our content draw at the bottom of the window + // this SHOULD have the same effect with that bug fixed and no others introduced... (thanks to devin on irc.badnik.net for confirming this logic) + if (pos > p->length - p->pagesize) + pos = p->length - p->pagesize; + if (pos < 0) + pos = 0; + + // Direct2D doesn't have a method for scrolling the existing contents of a render target. + // We'll have to just invalidate everything and hope for the best. + invalidateRect(a->hwnd, NULL, FALSE); + + *(p->pos) = pos; + + // now commit our new scrollbar setup... + ZeroMemory(&si, sizeof (SCROLLINFO)); + si.cbSize = sizeof (SCROLLINFO); + si.fMask = SIF_PAGE | SIF_POS | SIF_RANGE; + si.nPage = p->pagesize; + si.nMin = 0; + si.nMax = p->length - 1; // endpoint inclusive + si.nPos = *(p->pos); + SetScrollInfo(a->hwnd, which, &si, TRUE); +} + +static void scrollby(uiArea *a, int which, struct scrollParams *p, int delta) +{ + scrollto(a, which, p, *(p->pos) + delta); +} + +static void scroll(uiArea *a, int which, struct scrollParams *p, WPARAM wParam, LPARAM lParam) +{ + int pos; + SCROLLINFO si; + + pos = *(p->pos); + switch (LOWORD(wParam)) { + case SB_LEFT: // also SB_TOP + pos = 0; + break; + case SB_RIGHT: // also SB_BOTTOM + pos = p->length - p->pagesize; + break; + case SB_LINELEFT: // also SB_LINEUP + pos--; + break; + case SB_LINERIGHT: // also SB_LINEDOWN + pos++; + break; + case SB_PAGELEFT: // also SB_PAGEUP + pos -= p->pagesize; + break; + case SB_PAGERIGHT: // also SB_PAGEDOWN + pos += p->pagesize; + break; + case SB_THUMBPOSITION: + ZeroMemory(&si, sizeof (SCROLLINFO)); + si.cbSize = sizeof (SCROLLINFO); + si.fMask = SIF_POS; + if (GetScrollInfo(a->hwnd, which, &si) == 0) + logLastError(L"error getting thumb position for area"); + pos = si.nPos; + break; + case SB_THUMBTRACK: + ZeroMemory(&si, sizeof (SCROLLINFO)); + si.cbSize = sizeof (SCROLLINFO); + si.fMask = SIF_TRACKPOS; + if (GetScrollInfo(a->hwnd, which, &si) == 0) + logLastError(L"error getting thumb track position for area"); + pos = si.nTrackPos; + break; + } + scrollto(a, which, p, pos); +} + +static void wheelscroll(uiArea *a, int which, struct scrollParams *p, WPARAM wParam, LPARAM lParam) +{ + int delta; + int lines; + UINT scrollAmount; + + delta = GET_WHEEL_DELTA_WPARAM(wParam); + if (SystemParametersInfoW(p->wheelSPIAction, 0, &scrollAmount, 0) == 0) + // TODO use scrollAmount == 3 (for both v and h) instead? + logLastError(L"error getting area wheel scroll amount"); + if (scrollAmount == WHEEL_PAGESCROLL) + scrollAmount = p->pagesize; + if (scrollAmount == 0) // no mouse wheel scrolling (or t->pagesize == 0) + return; + // the rest of this is basically http://blogs.msdn.com/b/oldnewthing/archive/2003/08/07/54615.aspx and http://blogs.msdn.com/b/oldnewthing/archive/2003/08/11/54624.aspx + // see those pages for information on subtleties + delta += *(p->wheelCarry); + lines = delta * ((int) scrollAmount) / WHEEL_DELTA; + *(p->wheelCarry) = delta - lines * WHEEL_DELTA / ((int) scrollAmount); + scrollby(a, which, p, -lines); +} + +static void hscrollParams(uiArea *a, struct scrollParams *p) +{ + RECT r; + + ZeroMemory(p, sizeof (struct scrollParams)); + p->pos = &(a->hscrollpos); + // TODO get rid of these and replace with points + uiWindowsEnsureGetClientRect(a->hwnd, &r); + p->pagesize = r.right - r.left; + p->length = a->scrollWidth; + p->wheelCarry = &(a->hwheelCarry); + p->wheelSPIAction = SPI_GETWHEELSCROLLCHARS; +} + +static void hscrollto(uiArea *a, int pos) +{ + struct scrollParams p; + + hscrollParams(a, &p); + scrollto(a, SB_HORZ, &p, pos); +} + +static void hscrollby(uiArea *a, int delta) +{ + struct scrollParams p; + + hscrollParams(a, &p); + scrollby(a, SB_HORZ, &p, delta); +} + +static void hscroll(uiArea *a, WPARAM wParam, LPARAM lParam) +{ + struct scrollParams p; + + hscrollParams(a, &p); + scroll(a, SB_HORZ, &p, wParam, lParam); +} + +static void hwheelscroll(uiArea *a, WPARAM wParam, LPARAM lParam) +{ + struct scrollParams p; + + hscrollParams(a, &p); + wheelscroll(a, SB_HORZ, &p, wParam, lParam); +} + +static void vscrollParams(uiArea *a, struct scrollParams *p) +{ + RECT r; + + ZeroMemory(p, sizeof (struct scrollParams)); + p->pos = &(a->vscrollpos); + uiWindowsEnsureGetClientRect(a->hwnd, &r); + p->pagesize = r.bottom - r.top; + p->length = a->scrollHeight; + p->wheelCarry = &(a->vwheelCarry); + p->wheelSPIAction = SPI_GETWHEELSCROLLLINES; +} + +static void vscrollto(uiArea *a, int pos) +{ + struct scrollParams p; + + vscrollParams(a, &p); + scrollto(a, SB_VERT, &p, pos); +} + +static void vscrollby(uiArea *a, int delta) +{ + struct scrollParams p; + + vscrollParams(a, &p); + scrollby(a, SB_VERT, &p, delta); +} + +static void vscroll(uiArea *a, WPARAM wParam, LPARAM lParam) +{ + struct scrollParams p; + + vscrollParams(a, &p); + scroll(a, SB_VERT, &p, wParam, lParam); +} + +static void vwheelscroll(uiArea *a, WPARAM wParam, LPARAM lParam) +{ + struct scrollParams p; + + vscrollParams(a, &p); + wheelscroll(a, SB_VERT, &p, wParam, lParam); +} + +BOOL areaDoScroll(uiArea *a, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *lResult) +{ + switch (uMsg) { + case WM_HSCROLL: + hscroll(a, wParam, lParam); + *lResult = 0; + return TRUE; + case WM_MOUSEHWHEEL: + hwheelscroll(a, wParam, lParam); + *lResult = 0; + return TRUE; + case WM_VSCROLL: + vscroll(a, wParam, lParam); + *lResult = 0; + return TRUE; + case WM_MOUSEWHEEL: + vwheelscroll(a, wParam, lParam); + *lResult = 0; + return TRUE; + } + return FALSE; +} + +void areaScrollOnResize(uiArea *a, RECT *client) +{ + areaUpdateScroll(a); +} + +void areaUpdateScroll(uiArea *a) +{ + // use a no-op scroll to simulate scrolling + hscrollby(a, 0); + vscrollby(a, 0); +} diff --git a/dep/libui/windows/areautil.cpp b/dep/libui/windows/areautil.cpp new file mode 100644 index 0000000..9dc72fb --- /dev/null +++ b/dep/libui/windows/areautil.cpp @@ -0,0 +1,37 @@ +// 18 december 2015 +#include "uipriv_windows.hpp" +#include "area.hpp" + +void loadAreaSize(uiArea *a, ID2D1RenderTarget *rt, double *width, double *height) +{ + D2D1_SIZE_F size; + + *width = 0; + *height = 0; + if (!a->scrolling) { + if (rt == NULL) + rt = a->rt; + size = realGetSize(rt); + *width = size.width; + *height = size.height; + } +} + +void pixelsToDIP(uiArea *a, double *x, double *y) +{ + FLOAT dpix, dpiy; + + a->rt->GetDpi(&dpix, &dpiy); + // see https://msdn.microsoft.com/en-us/library/windows/desktop/dd756649%28v=vs.85%29.aspx (and others; search "direct2d mouse") + *x = (*x * 96) / dpix; + *y = (*y * 96) / dpiy; +} + +void dipToPixels(uiArea *a, double *x, double *y) +{ + FLOAT dpix, dpiy; + + a->rt->GetDpi(&dpix, &dpiy); + *x = (*x * dpix) / 96; + *y = (*y * dpiy) / 96; +} diff --git a/dep/libui/windows/attrstr.cpp b/dep/libui/windows/attrstr.cpp new file mode 100644 index 0000000..740ac43 --- /dev/null +++ b/dep/libui/windows/attrstr.cpp @@ -0,0 +1,427 @@ +// 12 february 2017 +#include "uipriv_windows.hpp" +#include "attrstr.hpp" + +// TODO this whole file needs cleanup + +// yep, even when it supports C++11, it doesn't support C++11 +// we require MSVC 2013; this was added in MSVC 2015 (https://msdn.microsoft.com/en-us/library/wfa0edys.aspx) +#ifdef _MSC_VER +#if _MSC_VER < 1900 +#define noexcept +#endif +#endif + +// we need to collect all the background parameters and add them all at once +// TODO consider having background parameters in the drawing effects +// TODO contextual alternates override ligatures? +// TODO rename this struct to something that isn't exclusively foreach-ing? +struct foreachParams { + const uint16_t *s; + size_t len; + IDWriteTextLayout *layout; + std::vector *backgroundParams; +}; + +static std::hash doubleHash; + +// we need to combine color and underline style into one unit for IDWriteLayout::SetDrawingEffect() +// we also want to combine identical effects, which DirectWrite doesn't seem to provide a way to do +// we can at least try to goad it into doing so if we can deduplicate effects once they're all computed +// so what we do is use this class to store in-progress effects, much like uiprivCombinedFontAttr on the OS X code +// we then deduplicate them later while converting them into a form suitable for drawing with; see applyEffectsAttributes() below +class combinedEffectsAttr : public IUnknown { + ULONG refcount; + uiAttribute *colorAttr; + uiAttribute *underlineAttr; + uiAttribute *underlineColorAttr; + + void setAttribute(uiAttribute *a) + { + if (a == NULL) + return; + switch (uiAttributeGetType(a)) { + case uiAttributeTypeColor: + if (this->colorAttr != NULL) + uiprivAttributeRelease(this->colorAttr); + this->colorAttr = uiprivAttributeRetain(a); + break; + case uiAttributeTypeUnderline: + if (this->underlineAttr != NULL) + uiprivAttributeRelease(this->underlineAttr); + this->underlineAttr = uiprivAttributeRetain(a); + break; + case uiAttributeTypeUnderlineColor: + if (this->underlineAttr != NULL) + uiprivAttributeRelease(this->underlineAttr); + this->underlineColorAttr = uiprivAttributeRetain(a); + break; + } + } + + // this is needed by applyEffectsAttributes() below + // TODO doesn't uiprivAttributeEqual() already do this; if it doesn't, make it so; if (or when) it does, fix all platforms to avoid this extra check + static bool attrEqual(uiAttribute *a, uiAttribute *b) + { + if (a == NULL && b == NULL) + return true; + if (a == NULL || b == NULL) + return false; + return uiprivAttributeEqual(a, b); + } +public: + combinedEffectsAttr(uiAttribute *a) + { + this->refcount = 1; + this->colorAttr = NULL; + this->underlineAttr = NULL; + this->underlineColorAttr = NULL; + this->setAttribute(a); + } + + ~combinedEffectsAttr() + { + if (this->colorAttr != NULL) + uiprivAttributeRelease(this->colorAttr); + if (this->underlineAttr != NULL) + uiprivAttributeRelease(this->underlineAttr); + if (this->underlineColorAttr != NULL) + uiprivAttributeRelease(this->underlineColorAttr); + } + + // IUnknown + virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) + { + if (ppvObject == NULL) + return E_POINTER; + if (riid == IID_IUnknown) { + this->AddRef(); + *ppvObject = this; + return S_OK; + } + *ppvObject = NULL; + return E_NOINTERFACE; + } + + virtual ULONG STDMETHODCALLTYPE AddRef(void) + { + this->refcount++; + return this->refcount; + } + + virtual ULONG STDMETHODCALLTYPE Release(void) + { + this->refcount--; + if (this->refcount == 0) { + delete this; + return 0; + } + return this->refcount; + } + + combinedEffectsAttr *cloneWith(uiAttribute *a) + { + combinedEffectsAttr *b; + + b = new combinedEffectsAttr(this->colorAttr); + b->setAttribute(this->underlineAttr); + b->setAttribute(this->underlineColorAttr); + b->setAttribute(a); + return b; + } + + // and these are also needed by applyEffectsAttributes() below + size_t hash(void) const noexcept + { + size_t ret = 0; + double r, g, b, a; + uiUnderlineColor colorType; + + if (this->colorAttr != NULL) { + uiAttributeColor(this->colorAttr, &r, &g, &b, &a); + ret ^= doubleHash(r); + ret ^= doubleHash(g); + ret ^= doubleHash(b); + ret ^= doubleHash(a); + } + if (this->underlineAttr != NULL) + ret ^= (size_t) uiAttributeUnderline(this->underlineAttr); + if (this->underlineColorAttr != NULL) { + uiAttributeUnderlineColor(this->underlineColorAttr, &colorType, &r, &g, &b, &a); + ret ^= (size_t) colorType; + ret ^= doubleHash(r); + ret ^= doubleHash(g); + ret ^= doubleHash(b); + ret ^= doubleHash(a); + } + return ret; + } + + bool equals(const combinedEffectsAttr *b) const + { + if (b == NULL) + return false; + return combinedEffectsAttr::attrEqual(this->colorAttr, b->colorAttr) && + combinedEffectsAttr::attrEqual(this->underlineAttr, b->underlineAttr) && + combinedEffectsAttr::attrEqual(this->underlineColorAttr, b->underlineColorAttr); + } + + drawingEffectsAttr *toDrawingEffectsAttr(void) + { + drawingEffectsAttr *dea; + double r, g, b, a; + uiUnderlineColor colorType; + + dea = new drawingEffectsAttr; + if (this->colorAttr != NULL) { + uiAttributeColor(this->colorAttr, &r, &g, &b, &a); + dea->setColor(r, g, b, a); + } + if (this->underlineAttr != NULL) + dea->setUnderline(uiAttributeUnderline(this->underlineAttr)); + if (this->underlineColorAttr != NULL) { + uiAttributeUnderlineColor(this->underlineColorAttr, &colorType, &r, &g, &b, &a); + // TODO see if Microsoft has any standard colors for these + switch (colorType) { + case uiUnderlineColorSpelling: + // TODO consider using the GtkTextView style property error-underline-color here if Microsoft has no preference + r = 1.0; + g = 0.0; + b = 0.0; + a = 1.0; + break; + case uiUnderlineColorGrammar: + r = 0.0; + g = 1.0; + b = 0.0; + a = 1.0; + break; + case uiUnderlineColorAuxiliary: + r = 0.0; + g = 0.0; + b = 1.0; + a = 1.0; + break; + } + dea->setUnderlineColor(r, g, b, a); + } + return dea; + } +}; + +// also needed by applyEffectsAttributes() below +// TODO provide all the fields of std::hash and std::equal_to? +class applyEffectsHash { +public: + typedef combinedEffectsAttr *ceaptr; + size_t operator()(applyEffectsHash::ceaptr const &cea) const noexcept + { + return cea->hash(); + } +}; + +class applyEffectsEqualTo { +public: + typedef combinedEffectsAttr *ceaptr; + bool operator()(const applyEffectsEqualTo::ceaptr &a, const applyEffectsEqualTo::ceaptr &b) const + { + return a->equals(b); + } +}; + +static HRESULT addEffectAttributeToRange(struct foreachParams *p, size_t start, size_t end, uiAttribute *attr) +{ + IUnknown *u; + combinedEffectsAttr *cea; + DWRITE_TEXT_RANGE range; + size_t diff; + HRESULT hr; + + while (start < end) { + hr = p->layout->GetDrawingEffect(start, &u, &range); + if (hr != S_OK) + return hr; + cea = (combinedEffectsAttr *) u; + if (cea == NULL) + cea = new combinedEffectsAttr(attr); + else + cea = cea->cloneWith(attr); + // clamp range within [start, end) + if (range.startPosition < start) { + diff = start - range.startPosition; + range.startPosition = start; + range.length -= diff; + } + if ((range.startPosition + range.length) > end) + range.length = end - range.startPosition; + hr = p->layout->SetDrawingEffect(cea, range); + // SetDrawingEffect will AddRef(), so Release() our copy + // (and we're abandoning early if that failed, so this will make sure things are cleaned up in that case) + cea->Release(); + if (hr != S_OK) + return hr; + start += range.length; + } + return S_OK; +} + +static void addBackgroundParams(struct foreachParams *p, size_t start, size_t end, const uiAttribute *attr) +{ + struct drawTextBackgroundParams *params; + + params = uiprivNew(struct drawTextBackgroundParams); + params->start = start; + params->end = end; + uiAttributeColor(attr, &(params->r), &(params->g), &(params->b), &(params->a)); + p->backgroundParams->push_back(params); +} + +static uiForEach processAttribute(const uiAttributedString *s, const uiAttribute *attr, size_t start, size_t end, void *data) +{ + struct foreachParams *p = (struct foreachParams *) data; + DWRITE_TEXT_RANGE range; + WCHAR *wfamily; + BOOL hasUnderline; + IDWriteTypography *dt; + HRESULT hr; + + start = uiprivAttributedStringUTF8ToUTF16(s, start); + end = uiprivAttributedStringUTF8ToUTF16(s, end); + range.startPosition = start; + range.length = end - start; + switch (uiAttributeGetType(attr)) { + case uiAttributeTypeFamily: + wfamily = toUTF16(uiAttributeFamily(attr)); + hr = p->layout->SetFontFamilyName(wfamily, range); + if (hr != S_OK) + logHRESULT(L"error applying family name attribute", hr); + uiprivFree(wfamily); + break; + case uiAttributeTypeSize: + hr = p->layout->SetFontSize( +// TODO unify with fontmatch.cpp and/or attrstr.hpp +#define pointSizeToDWriteSize(size) (size * (96.0 / 72.0)) + pointSizeToDWriteSize(uiAttributeSize(attr)), + range); + if (hr != S_OK) + logHRESULT(L"error applying size attribute", hr); + break; + case uiAttributeTypeWeight: + hr = p->layout->SetFontWeight( + uiprivWeightToDWriteWeight(uiAttributeWeight(attr)), + range); + if (hr != S_OK) + logHRESULT(L"error applying weight attribute", hr); + break; + case uiAttributeTypeItalic: + hr = p->layout->SetFontStyle( + uiprivItalicToDWriteStyle(uiAttributeItalic(attr)), + range); + if (hr != S_OK) + logHRESULT(L"error applying italic attribute", hr); + break; + case uiAttributeTypeStretch: + hr = p->layout->SetFontStretch( + uiprivStretchToDWriteStretch(uiAttributeStretch(attr)), + range); + if (hr != S_OK) + logHRESULT(L"error applying stretch attribute", hr); + break; + case uiAttributeTypeUnderline: + // mark that we have an underline; otherwise, DirectWrite will never call our custom renderer's DrawUnderline() method + hasUnderline = FALSE; + if (uiAttributeUnderline(attr) != uiUnderlineNone) + hasUnderline = TRUE; + hr = p->layout->SetUnderline(hasUnderline, range); + if (hr != S_OK) + logHRESULT(L"error applying underline attribute", hr); + // and fall through to set the underline style through the drawing effect + case uiAttributeTypeColor: + case uiAttributeTypeUnderlineColor: + // TODO const-correct this properly + hr = addEffectAttributeToRange(p, start, end, (uiAttribute *) attr); + if (hr != S_OK) + logHRESULT(L"error applying effect (color, underline, or underline color) attribute", hr); + break; + case uiAttributeTypeBackground: + addBackgroundParams(p, start, end, attr); + break; + case uiAttributeTypeFeatures: + // only generate an attribute if not NULL + // TODO do we still need to do this or not... + if (uiAttributeFeatures(attr) == NULL) + break; + dt = uiprivOpenTypeFeaturesToIDWriteTypography(uiAttributeFeatures(attr)); + hr = p->layout->SetTypography(dt, range); + if (hr != S_OK) + logHRESULT(L"error applying features attribute", hr); + dt->Release(); + break; + } + return uiForEachContinue; +} + +static HRESULT applyEffectsAttributes(struct foreachParams *p) +{ + IUnknown *u; + combinedEffectsAttr *cea; + drawingEffectsAttr *dea; + DWRITE_TEXT_RANGE range; + // here's the magic: this std::unordered_map will deduplicate all of our combinedEffectsAttrs, mapping all identical ones to a single drawingEffectsAttr + // because drawingEffectsAttr is the *actual* drawing effect we want for rendering, we also replace the combinedEffectsAttrs with them in the IDWriteTextLayout at the same time + // note the use of our custom hash and equal_to implementations + std::unordered_map effects; + HRESULT hr; + + // go through, replacing every combinedEffectsAttr with the proper drawingEffectsAttr + range.startPosition = 0; + // and in case this while loop never runs, make hr valid to start with + hr = S_OK; + while (range.startPosition < p->len) { + hr = p->layout->GetDrawingEffect(range.startPosition, &u, &range); + if (hr != S_OK) + // note that we are breaking instead of returning; this allows us to clean up on failure + break; + cea = (combinedEffectsAttr *) u; + if (cea != NULL) { + auto diter = effects.find(cea); + if (diter != effects.end()) + dea = diter->second; + else { + dea = cea->toDrawingEffectsAttr(); + effects.insert({cea, dea}); + } + hr = p->layout->SetDrawingEffect(dea, range); + // don't release dea; we need the reference that's inside the map + // (we don't take extra references on lookup, so this will be fine) + if (hr != S_OK) + break; + } + range.startPosition += range.length; + } + + // and clean up, finally destroying the combinedEffectAttrs too + // we do this in the case of failure as well, to make sure everything is properly cleaned up + for (auto iter = effects.begin(); iter != effects.end(); iter++) { + iter->first->Release(); + iter->second->Release(); + } + return hr; +} + +void uiprivAttributedStringApplyAttributesToDWriteTextLayout(uiDrawTextLayoutParams *p, IDWriteTextLayout *layout, std::vector **backgroundParams) +{ + struct foreachParams fep; + HRESULT hr; + + fep.s = uiprivAttributedStringUTF16String(p->String); + fep.len = uiprivAttributedStringUTF16Len(p->String); + fep.layout = layout; + fep.backgroundParams = new std::vector; + uiAttributedStringForEachAttribute(p->String, processAttribute, &fep); + hr = applyEffectsAttributes(&fep); + if (hr != S_OK) + logHRESULT(L"error applying effects attributes", hr); + *backgroundParams = fep.backgroundParams; +} diff --git a/dep/libui/windows/attrstr.hpp b/dep/libui/windows/attrstr.hpp new file mode 100644 index 0000000..bd522ca --- /dev/null +++ b/dep/libui/windows/attrstr.hpp @@ -0,0 +1,85 @@ +// 11 march 2018 +#include "../common/attrstr.h" + +// dwrite.cpp +extern IDWriteFactory *dwfactory; +extern HRESULT uiprivInitDrawText(void); +extern void uiprivUninitDrawText(void); +struct fontCollection { + IDWriteFontCollection *fonts; + WCHAR userLocale[LOCALE_NAME_MAX_LENGTH]; + int userLocaleSuccess; +}; +extern fontCollection *uiprivLoadFontCollection(void); +extern WCHAR *uiprivFontCollectionFamilyName(fontCollection *fc, IDWriteFontFamily *family); +extern void uiprivFontCollectionFree(fontCollection *fc); +extern WCHAR *uiprivFontCollectionCorrectString(fontCollection *fc, IDWriteLocalizedStrings *names); + +// opentype.cpp +extern IDWriteTypography *uiprivOpenTypeFeaturesToIDWriteTypography(const uiOpenTypeFeatures *otf); + +// fontmatch.cpp +extern DWRITE_FONT_WEIGHT uiprivWeightToDWriteWeight(uiTextWeight w); +extern DWRITE_FONT_STYLE uiprivItalicToDWriteStyle(uiTextItalic i); +extern DWRITE_FONT_STRETCH uiprivStretchToDWriteStretch(uiTextStretch s); +extern void uiprivFontDescriptorFromIDWriteFont(IDWriteFont *font, uiFontDescriptor *uidesc); + +// attrstr.cpp +// TODO +struct drawTextBackgroundParams; +extern void uiprivAttributedStringApplyAttributesToDWriteTextLayout(uiDrawTextLayoutParams *p, IDWriteTextLayout *layout, std::vector **backgroundFuncs); + +// drawtext.cpp +class drawingEffectsAttr : public IUnknown { + ULONG refcount; + + bool hasColor; + double r; + double g; + double b; + double a; + + bool hasUnderline; + uiUnderline u; + + bool hasUnderlineColor; + double ur; + double ug; + double ub; + double ua; +public: + drawingEffectsAttr(void); + + // IUnknown + virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject); + virtual ULONG STDMETHODCALLTYPE AddRef(void); + virtual ULONG STDMETHODCALLTYPE Release(void); + + void setColor(double r, double g, double b, double a); + void setUnderline(uiUnderline u); + void setUnderlineColor(double r, double g, double b, double a); + HRESULT mkColorBrush(ID2D1RenderTarget *rt, ID2D1SolidColorBrush **b); + HRESULT underline(uiUnderline *u); + HRESULT mkUnderlineBrush(ID2D1RenderTarget *rt, ID2D1SolidColorBrush **b); +}; +// TODO figure out where this type should *really* go in all the headers... +struct drawTextBackgroundParams { + size_t start; + size_t end; + double r; + double g; + double b; + double a; +}; + +// fontdialog.cpp +struct fontDialogParams { + IDWriteFont *font; + double size; + WCHAR *familyName; + WCHAR *styleName; +}; +extern BOOL uiprivShowFontDialog(HWND parent, struct fontDialogParams *params); +extern void uiprivLoadInitialFontDialogParams(struct fontDialogParams *params); +extern void uiprivDestroyFontDialogParams(struct fontDialogParams *params); +extern WCHAR *uiprivFontDialogParamsToString(struct fontDialogParams *params); diff --git a/dep/libui/windows/box.cpp b/dep/libui/windows/box.cpp new file mode 100644 index 0000000..9567954 --- /dev/null +++ b/dep/libui/windows/box.cpp @@ -0,0 +1,320 @@ +// 7 april 2015 +#include "uipriv_windows.hpp" + +struct boxChild { + uiControl *c; + int stretchy; + int width; + int height; +}; + +struct uiBox { + uiWindowsControl c; + HWND hwnd; + std::vector *controls; + int vertical; + int padded; +}; + +static void boxPadding(uiBox *b, int *xpadding, int *ypadding) +{ + uiWindowsSizing sizing; + + *xpadding = 0; + *ypadding = 0; + if (b->padded) { + uiWindowsGetSizing(b->hwnd, &sizing); + uiWindowsSizingStandardPadding(&sizing, xpadding, ypadding); + } +} + +static void boxRelayout(uiBox *b) +{ + RECT r; + int x, y, width, height; + int xpadding, ypadding; + int nStretchy; + int stretchywid, stretchyht; + int i; + int minimumWidth, minimumHeight; + int nVisible; + uiWindowsSizing *d; + + if (b->controls->size() == 0) + return; + + uiWindowsEnsureGetClientRect(b->hwnd, &r); + x = r.left; + y = r.top; + width = r.right - r.left; + height = r.bottom - r.top; + + // -1) get this Box's padding + boxPadding(b, &xpadding, &ypadding); + + // 1) get width and height of non-stretchy controls + // this will tell us how much space will be left for stretchy controls + stretchywid = width; + stretchyht = height; + nStretchy = 0; + nVisible = 0; + for (struct boxChild &bc : *(b->controls)) { + if (!uiControlVisible(bc.c)) + continue; + nVisible++; + if (bc.stretchy) { + nStretchy++; + continue; + } + uiWindowsControlMinimumSize(uiWindowsControl(bc.c), &minimumWidth, &minimumHeight); + if (b->vertical) { // all controls have same width + bc.width = width; + bc.height = minimumHeight; + stretchyht -= minimumHeight; + } else { // all controls have same height + bc.width = minimumWidth; + bc.height = height; + stretchywid -= minimumWidth; + } + } + if (nVisible == 0) // nothing to do + return; + + // 2) now inset the available rect by the needed padding + if (b->vertical) { + height -= (nVisible - 1) * ypadding; + stretchyht -= (nVisible - 1) * ypadding; + } else { + width -= (nVisible - 1) * xpadding; + stretchywid -= (nVisible - 1) * xpadding; + } + + // 3) now get the size of stretchy controls + if (nStretchy != 0) { + if (b->vertical) + stretchyht /= nStretchy; + else + stretchywid /= nStretchy; + for (struct boxChild &bc : *(b->controls)) { + if (!uiControlVisible(bc.c)) + continue; + if (bc.stretchy) { + bc.width = stretchywid; + bc.height = stretchyht; + } + } + } + + // 4) now we can position controls + // first, make relative to the top-left corner of the container + x = 0; + y = 0; + for (const struct boxChild &bc : *(b->controls)) { + if (!uiControlVisible(bc.c)) + continue; + uiWindowsEnsureMoveWindowDuringResize((HWND) uiControlHandle(bc.c), x, y, bc.width, bc.height); + if (b->vertical) + y += bc.height + ypadding; + else + x += bc.width + xpadding; + } +} + +static void uiBoxDestroy(uiControl *c) +{ + uiBox *b = uiBox(c); + + for (const struct boxChild &bc : *(b->controls)) { + uiControlSetParent(bc.c, NULL); + uiControlDestroy(bc.c); + } + delete b->controls; + uiWindowsEnsureDestroyWindow(b->hwnd); + uiFreeControl(uiControl(b)); +} + +uiWindowsControlDefaultHandle(uiBox) +uiWindowsControlDefaultParent(uiBox) +uiWindowsControlDefaultSetParent(uiBox) +uiWindowsControlDefaultToplevel(uiBox) +uiWindowsControlDefaultVisible(uiBox) +uiWindowsControlDefaultShow(uiBox) +uiWindowsControlDefaultHide(uiBox) +uiWindowsControlDefaultEnabled(uiBox) +uiWindowsControlDefaultEnable(uiBox) +uiWindowsControlDefaultDisable(uiBox) + +static void uiBoxSyncEnableState(uiWindowsControl *c, int enabled) +{ + uiBox *b = uiBox(c); + + if (uiWindowsShouldStopSyncEnableState(uiWindowsControl(b), enabled)) + return; + for (const struct boxChild &bc : *(b->controls)) + uiWindowsControlSyncEnableState(uiWindowsControl(bc.c), enabled); +} + +uiWindowsControlDefaultSetParentHWND(uiBox) + +static void uiBoxMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + uiBox *b = uiBox(c); + int xpadding, ypadding; + int nStretchy; + // these two contain the largest minimum width and height of all stretchy controls in the box + // all stretchy controls will use this value to determine the final minimum size + int maxStretchyWidth, maxStretchyHeight; + int i; + int minimumWidth, minimumHeight; + int nVisible; + uiWindowsSizing sizing; + + *width = 0; + *height = 0; + if (b->controls->size() == 0) + return; + + // 0) get this Box's padding + boxPadding(b, &xpadding, &ypadding); + + // 1) add in the size of non-stretchy controls and get (but not add in) the largest widths and heights of stretchy controls + // we still add in like direction of stretchy controls + nStretchy = 0; + maxStretchyWidth = 0; + maxStretchyHeight = 0; + nVisible = 0; + for (const struct boxChild &bc : *(b->controls)) { + if (!uiControlVisible(bc.c)) + continue; + nVisible++; + uiWindowsControlMinimumSize(uiWindowsControl(bc.c), &minimumWidth, &minimumHeight); + if (bc.stretchy) { + nStretchy++; + if (maxStretchyWidth < minimumWidth) + maxStretchyWidth = minimumWidth; + if (maxStretchyHeight < minimumHeight) + maxStretchyHeight = minimumHeight; + } + if (b->vertical) { + if (*width < minimumWidth) + *width = minimumWidth; + if (!bc.stretchy) + *height += minimumHeight; + } else { + if (!bc.stretchy) + *width += minimumWidth; + if (*height < minimumHeight) + *height = minimumHeight; + } + } + if (nVisible == 0) // just return 0x0 + return; + + // 2) now outset the desired rect with the needed padding + if (b->vertical) + *height += (nVisible - 1) * ypadding; + else + *width += (nVisible - 1) * xpadding; + + // 3) and now we can add in stretchy controls + if (b->vertical) + *height += nStretchy * maxStretchyHeight; + else + *width += nStretchy * maxStretchyWidth; +} + +static void uiBoxMinimumSizeChanged(uiWindowsControl *c) +{ + uiBox *b = uiBox(c); + + if (uiWindowsControlTooSmall(uiWindowsControl(b))) { + uiWindowsControlContinueMinimumSizeChanged(uiWindowsControl(b)); + return; + } + boxRelayout(b); +} + +uiWindowsControlDefaultLayoutRect(uiBox) +uiWindowsControlDefaultAssignControlIDZOrder(uiBox) + +static void uiBoxChildVisibilityChanged(uiWindowsControl *c) +{ + // TODO eliminate the redundancy + uiWindowsControlMinimumSizeChanged(c); +} + +static void boxArrangeChildren(uiBox *b) +{ + LONG_PTR controlID; + HWND insertAfter; + + controlID = 100; + insertAfter = NULL; + for (const struct boxChild &bc : *(b->controls)) + uiWindowsControlAssignControlIDZOrder(uiWindowsControl(bc.c), &controlID, &insertAfter); +} + +void uiBoxAppend(uiBox *b, uiControl *c, int stretchy) +{ + struct boxChild bc; + + bc.c = c; + bc.stretchy = stretchy; + uiControlSetParent(bc.c, uiControl(b)); + uiWindowsControlSetParentHWND(uiWindowsControl(bc.c), b->hwnd); + b->controls->push_back(bc); + boxArrangeChildren(b); + uiWindowsControlMinimumSizeChanged(uiWindowsControl(b)); +} + +void uiBoxDelete(uiBox *b, int index) +{ + uiControl *c; + + c = (*(b->controls))[index].c; + uiControlSetParent(c, NULL); + uiWindowsControlSetParentHWND(uiWindowsControl(c), NULL); + b->controls->erase(b->controls->begin() + index); + boxArrangeChildren(b); + uiWindowsControlMinimumSizeChanged(uiWindowsControl(b)); +} + +int uiBoxPadded(uiBox *b) +{ + return b->padded; +} + +void uiBoxSetPadded(uiBox *b, int padded) +{ + b->padded = padded; + uiWindowsControlMinimumSizeChanged(uiWindowsControl(b)); +} + +static void onResize(uiWindowsControl *c) +{ + boxRelayout(uiBox(c)); +} + +static uiBox *finishNewBox(int vertical) +{ + uiBox *b; + + uiWindowsNewControl(uiBox, b); + + b->hwnd = uiWindowsMakeContainer(uiWindowsControl(b), onResize); + + b->vertical = vertical; + b->controls = new std::vector; + + return b; +} + +uiBox *uiNewHorizontalBox(void) +{ + return finishNewBox(0); +} + +uiBox *uiNewVerticalBox(void) +{ + return finishNewBox(1); +} diff --git a/dep/libui/windows/button.cpp b/dep/libui/windows/button.cpp new file mode 100644 index 0000000..d8913ec --- /dev/null +++ b/dep/libui/windows/button.cpp @@ -0,0 +1,104 @@ +// 7 april 2015 +#include "uipriv_windows.hpp" + +struct uiButton { + uiWindowsControl c; + HWND hwnd; + void (*onClicked)(uiButton *, void *); + void *onClickedData; +}; + +static BOOL onWM_COMMAND(uiControl *c, HWND hwnd, WORD code, LRESULT *lResult) +{ + uiButton *b = uiButton(c); + + if (code != BN_CLICKED) + return FALSE; + (*(b->onClicked))(b, b->onClickedData); + *lResult = 0; + return TRUE; +} + +static void uiButtonDestroy(uiControl *c) +{ + uiButton *b = uiButton(c); + + uiWindowsUnregisterWM_COMMANDHandler(b->hwnd); + uiWindowsEnsureDestroyWindow(b->hwnd); + uiFreeControl(uiControl(b)); +} + +uiWindowsControlAllDefaultsExceptDestroy(uiButton) + +// from http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing +#define buttonHeight 14 + +static void uiButtonMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + uiButton *b = uiButton(c); + SIZE size; + uiWindowsSizing sizing; + int y; + + // try the comctl32 version 6 way + size.cx = 0; // explicitly ask for ideal size + size.cy = 0; + if (SendMessageW(b->hwnd, BCM_GETIDEALSIZE, 0, (LPARAM) (&size)) != FALSE) { + *width = size.cx; + *height = size.cy; + return; + } + + // that didn't work; fall back to using Microsoft's metrics + // Microsoft says to use a fixed width for all buttons; this isn't good enough + // use the text width instead, with some edge padding + *width = uiWindowsWindowTextWidth(b->hwnd) + (2 * GetSystemMetrics(SM_CXEDGE)); + y = buttonHeight; + uiWindowsGetSizing(b->hwnd, &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, NULL, &y); + *height = y; +} + +static void defaultOnClicked(uiButton *b, void *data) +{ + // do nothing +} + +char *uiButtonText(uiButton *b) +{ + return uiWindowsWindowText(b->hwnd); +} + +void uiButtonSetText(uiButton *b, const char *text) +{ + uiWindowsSetWindowText(b->hwnd, text); + // changing the text might necessitate a change in the button's size + uiWindowsControlMinimumSizeChanged(uiWindowsControl(b)); +} + +void uiButtonOnClicked(uiButton *b, void (*f)(uiButton *, void *), void *data) +{ + b->onClicked = f; + b->onClickedData = data; +} + +uiButton *uiNewButton(const char *text) +{ + uiButton *b; + WCHAR *wtext; + + uiWindowsNewControl(uiButton, b); + + wtext = toUTF16(text); + b->hwnd = uiWindowsEnsureCreateControlHWND(0, + L"button", wtext, + BS_PUSHBUTTON | WS_TABSTOP, + hInstance, NULL, + TRUE); + uiprivFree(wtext); + + uiWindowsRegisterWM_COMMANDHandler(b->hwnd, onWM_COMMAND, uiControl(b)); + uiButtonOnClicked(b, defaultOnClicked, NULL); + + return b; +} diff --git a/dep/libui/windows/checkbox.cpp b/dep/libui/windows/checkbox.cpp new file mode 100644 index 0000000..3d8c92e --- /dev/null +++ b/dep/libui/windows/checkbox.cpp @@ -0,0 +1,117 @@ +// 7 april 2015 +#include "uipriv_windows.hpp" + +struct uiCheckbox { + uiWindowsControl c; + HWND hwnd; + void (*onToggled)(uiCheckbox *, void *); + void *onToggledData; +}; + +static BOOL onWM_COMMAND(uiControl *cc, HWND hwnd, WORD code, LRESULT *lResult) +{ + uiCheckbox *c = uiCheckbox(cc); + WPARAM check; + + if (code != BN_CLICKED) + return FALSE; + + // we didn't use BS_AUTOCHECKBOX (http://blogs.msdn.com/b/oldnewthing/archive/2014/05/22/10527522.aspx) so we have to manage the check state ourselves + check = BST_CHECKED; + if (SendMessage(c->hwnd, BM_GETCHECK, 0, 0) == BST_CHECKED) + check = BST_UNCHECKED; + SendMessage(c->hwnd, BM_SETCHECK, check, 0); + + (*(c->onToggled))(c, c->onToggledData); + *lResult = 0; + return TRUE; +} + +static void uiCheckboxDestroy(uiControl *cc) +{ + uiCheckbox *c = uiCheckbox(cc); + + uiWindowsUnregisterWM_COMMANDHandler(c->hwnd); + uiWindowsEnsureDestroyWindow(c->hwnd); + uiFreeControl(uiControl(c)); +} + +uiWindowsControlAllDefaultsExceptDestroy(uiCheckbox) + +// from http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing +#define checkboxHeight 10 +// from http://msdn.microsoft.com/en-us/library/windows/desktop/bb226818%28v=vs.85%29.aspx +#define checkboxXFromLeftOfBoxToLeftOfLabel 12 + +static void uiCheckboxMinimumSize(uiWindowsControl *cc, int *width, int *height) +{ + uiCheckbox *c = uiCheckbox(cc); + uiWindowsSizing sizing; + int x, y; + + x = checkboxXFromLeftOfBoxToLeftOfLabel; + y = checkboxHeight; + uiWindowsGetSizing(c->hwnd, &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, &x, &y); + *width = x + uiWindowsWindowTextWidth(c->hwnd); + *height = y; +} + +static void defaultOnToggled(uiCheckbox *c, void *data) +{ + // do nothing +} + +char *uiCheckboxText(uiCheckbox *c) +{ + return uiWindowsWindowText(c->hwnd); +} + +void uiCheckboxSetText(uiCheckbox *c, const char *text) +{ + uiWindowsSetWindowText(c->hwnd, text); + // changing the text might necessitate a change in the checkbox's size + uiWindowsControlMinimumSizeChanged(uiWindowsControl(c)); +} + +void uiCheckboxOnToggled(uiCheckbox *c, void (*f)(uiCheckbox *, void *), void *data) +{ + c->onToggled = f; + c->onToggledData = data; +} + +int uiCheckboxChecked(uiCheckbox *c) +{ + return SendMessage(c->hwnd, BM_GETCHECK, 0, 0) == BST_CHECKED; +} + +void uiCheckboxSetChecked(uiCheckbox *c, int checked) +{ + WPARAM check; + + check = BST_CHECKED; + if (!checked) + check = BST_UNCHECKED; + SendMessage(c->hwnd, BM_SETCHECK, check, 0); +} + +uiCheckbox *uiNewCheckbox(const char *text) +{ + uiCheckbox *c; + WCHAR *wtext; + + uiWindowsNewControl(uiCheckbox, c); + + wtext = toUTF16(text); + c->hwnd = uiWindowsEnsureCreateControlHWND(0, + L"button", wtext, + BS_CHECKBOX | WS_TABSTOP, + hInstance, NULL, + TRUE); + uiprivFree(wtext); + + uiWindowsRegisterWM_COMMANDHandler(c->hwnd, onWM_COMMAND, uiControl(c)); + uiCheckboxOnToggled(c, defaultOnToggled, NULL); + + return c; +} diff --git a/dep/libui/windows/colorbutton.cpp b/dep/libui/windows/colorbutton.cpp new file mode 100644 index 0000000..c1ba695 --- /dev/null +++ b/dep/libui/windows/colorbutton.cpp @@ -0,0 +1,192 @@ +// 16 may 2016 +#include "uipriv_windows.hpp" + +struct uiColorButton { + uiWindowsControl c; + HWND hwnd; + double r; + double g; + double b; + double a; + void (*onChanged)(uiColorButton *, void *); + void *onChangedData; +}; + +static void uiColorButtonDestroy(uiControl *c) +{ + uiColorButton *b = uiColorButton(c); + + uiWindowsUnregisterWM_COMMANDHandler(b->hwnd); + uiWindowsUnregisterWM_NOTIFYHandler(b->hwnd); + uiWindowsEnsureDestroyWindow(b->hwnd); + uiFreeControl(uiControl(b)); +} + +static BOOL onWM_COMMAND(uiControl *c, HWND hwnd, WORD code, LRESULT *lResult) +{ + uiColorButton *b = uiColorButton(c); + HWND parent; + struct colorDialogRGBA rgba; + + if (code != BN_CLICKED) + return FALSE; + + parent = parentToplevel(b->hwnd); + rgba.r = b->r; + rgba.g = b->g; + rgba.b = b->b; + rgba.a = b->a; + if (showColorDialog(parent, &rgba)) { + b->r = rgba.r; + b->g = rgba.g; + b->b = rgba.b; + b->a = rgba.a; + invalidateRect(b->hwnd, NULL, TRUE); + (*(b->onChanged))(b, b->onChangedData); + } + + *lResult = 0; + return TRUE; +} + +static BOOL onWM_NOTIFY(uiControl *c, HWND hwnd, NMHDR *nmhdr, LRESULT *lResult) +{ + uiColorButton *b = uiColorButton(c); + NMCUSTOMDRAW *nm = (NMCUSTOMDRAW *) nmhdr; + RECT client; + ID2D1DCRenderTarget *rt; + D2D1_RECT_F r; + D2D1_COLOR_F color; + D2D1_BRUSH_PROPERTIES bprop; + ID2D1SolidColorBrush *brush; + uiWindowsSizing sizing; + int x, y; + HRESULT hr; + + if (nmhdr->code != NM_CUSTOMDRAW) + return FALSE; + // and allow the button to draw its background + if (nm->dwDrawStage != CDDS_PREPAINT) + return FALSE; + + uiWindowsEnsureGetClientRect(b->hwnd, &client); + rt = makeHDCRenderTarget(nm->hdc, &client); + rt->BeginDraw(); + + uiWindowsGetSizing(b->hwnd, &sizing); + x = 3; // should be enough + y = 3; + uiWindowsSizingDlgUnitsToPixels(&sizing, &x, &y); + r.left = client.left + x; + r.top = client.top + y; + r.right = client.right - x; + r.bottom = client.bottom - y; + + color.r = b->r; + color.g = b->g; + color.b = b->b; + color.a = b->a; + ZeroMemory(&bprop, sizeof (D2D1_BRUSH_PROPERTIES)); + bprop.opacity = 1.0; + bprop.transform._11 = 1; + bprop.transform._22 = 1; + hr = rt->CreateSolidColorBrush(&color, &bprop, &brush); + if (hr != S_OK) + logHRESULT(L"error creating brush for color button", hr); + rt->FillRectangle(&r, brush); + brush->Release(); + + hr = rt->EndDraw(NULL, NULL); + if (hr != S_OK) + logHRESULT(L"error drawing color on color button", hr); + rt->Release(); + + // skip default processing (don't draw text) + *lResult = CDRF_SKIPDEFAULT; + return TRUE; +} + +uiWindowsControlAllDefaultsExceptDestroy(uiColorButton) + +// from http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing +#define buttonHeight 14 + +// TODO check widths +static void uiColorButtonMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + uiColorButton *b = uiColorButton(c); + SIZE size; + uiWindowsSizing sizing; + int y; + + // try the comctl32 version 6 way + size.cx = 0; // explicitly ask for ideal size + size.cy = 0; + if (SendMessageW(b->hwnd, BCM_GETIDEALSIZE, 0, (LPARAM) (&size)) != FALSE) { + *width = size.cx; + *height = size.cy; + return; + } + + // that didn't work; fall back to using Microsoft's metrics + // Microsoft says to use a fixed width for all buttons; this isn't good enough + // use the text width instead, with some edge padding + *width = uiWindowsWindowTextWidth(b->hwnd) + (2 * GetSystemMetrics(SM_CXEDGE)); + y = buttonHeight; + uiWindowsGetSizing(b->hwnd, &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, NULL, &y); + *height = y; +} + +static void defaultOnChanged(uiColorButton *b, void *data) +{ + // do nothing +} + +void uiColorButtonColor(uiColorButton *b, double *r, double *g, double *bl, double *a) +{ + *r = b->r; + *g = b->g; + *bl = b->b; + *a = b->a; +} + +void uiColorButtonSetColor(uiColorButton *b, double r, double g, double bl, double a) +{ + b->r = r; + b->g = g; + b->b = bl; + b->a = a; + invalidateRect(b->hwnd, NULL, TRUE); +} + +void uiColorButtonOnChanged(uiColorButton *b, void (*f)(uiColorButton *, void *), void *data) +{ + b->onChanged = f; + b->onChangedData = data; +} + +uiColorButton *uiNewColorButton(void) +{ + uiColorButton *b; + + uiWindowsNewControl(uiColorButton, b); + + // initial color is black + b->r = 0.0; + b->g = 0.0; + b->b = 0.0; + b->a = 1.0; + + b->hwnd = uiWindowsEnsureCreateControlHWND(0, + L"button", L" ", // TODO; can't use "" TODO + BS_PUSHBUTTON | WS_TABSTOP, + hInstance, NULL, + TRUE); + + uiWindowsRegisterWM_COMMANDHandler(b->hwnd, onWM_COMMAND, uiControl(b)); + uiWindowsRegisterWM_NOTIFYHandler(b->hwnd, onWM_NOTIFY, uiControl(b)); + uiColorButtonOnChanged(b, defaultOnChanged, NULL); + + return b; +} diff --git a/dep/libui/windows/colordialog.cpp b/dep/libui/windows/colordialog.cpp new file mode 100644 index 0000000..a04c446 --- /dev/null +++ b/dep/libui/windows/colordialog.cpp @@ -0,0 +1,1457 @@ +// 16 may 2016 +#include "uipriv_windows.hpp" + +// TODO should the d2dscratch programs capture mouse? + +struct colorDialog { + HWND hwnd; + + HWND svChooser; + HWND hSlider; + HWND preview; + HWND opacitySlider; + HWND editH; + HWND editS; + HWND editV; + HWND editRDouble, editRInt; + HWND editGDouble, editGInt; + HWND editBDouble, editBInt; + HWND editADouble, editAInt; + HWND editHex; + + double h; + double s; + double v; + double a; + struct colorDialogRGBA *out; + + BOOL updating; +}; + +// both of these are from the wikipedia page on HSV +// TODO what to do about negative h? +static void rgb2HSV(double r, double g, double b, double *h, double *s, double *v) +{ + double M, m; + int whichmax; + double c; + + M = r; + whichmax = 0; + if (M < g) { + M = g; + whichmax = 1; + } + if (M < b) { + M = b; + whichmax = 2; + } + m = r; + if (m > g) + m = g; + if (m > b) + m = b; + c = M - m; + + if (c == 0) + *h = 0; + else { + switch (whichmax) { + case 0: + *h = ((g - b) / c); + *h = fmod(*h, 6); + break; + case 1: + *h = ((b - r) / c) + 2; + break; + case 2: + *h = ((r - g) / c) + 4; + break; + } + *h /= 6; // put in range [0,1) + } + + *v = M; + + if (c == 0) + *s = 0; + else + *s = c / *v; +} + +// TODO negative R values? +static void hsv2RGB(double h, double s, double v, double *r, double *g, double *b) +{ + double c; + double hPrime; + int h60; + double x; + double m; + double c1, c2; + + c = v * s; + hPrime = h * 6; + h60 = (int) hPrime; // equivalent to splitting into 60° chunks + x = c * (1.0 - fabs(fmod(hPrime, 2) - 1.0)); + m = v - c; + switch (h60) { + case 0: + *r = c + m; + *g = x + m; + *b = m; + return; + case 1: + *r = x + m; + *g = c + m; + *b = m; + return; + case 2: + *r = m; + *g = c + m; + *b = x + m; + return; + case 3: + *r = m; + *g = x + m; + *b = c + m; + return; + case 4: + *r = x + m; + *g = m; + *b = c + m; + return; + case 5: + *r = c + m; + *g = m; + *b = x + m; + return; + } + // TODO +} + +#define hexd L"0123456789ABCDEF" + +static void rgba2Hex(uint8_t r, uint8_t g, uint8_t b, uint8_t a, WCHAR *buf) +{ + buf[0] = L'#'; + buf[1] = hexd[(a >> 4) & 0xF]; + buf[2] = hexd[a & 0xF]; + buf[3] = hexd[(r >> 4) & 0xF]; + buf[4] = hexd[r & 0xF]; + buf[5] = hexd[(g >> 4) & 0xF]; + buf[6] = hexd[g & 0xF]; + buf[7] = hexd[(b >> 4) & 0xF]; + buf[8] = hexd[b & 0xF]; + buf[9] = L'\0'; +} + +static int convHexDigit(WCHAR c) +{ + if (c >= L'0' && c <= L'9') + return c - L'0'; + if (c >= L'A' && c <= L'F') + return c - L'A' + 0xA; + if (c >= L'a' && c <= L'f') + return c - L'a' + 0xA; + return -1; +} + +// TODO allow #NNN shorthand +static BOOL hex2RGBA(WCHAR *buf, double *r, double *g, double *b, double *a) +{ + uint8_t component; + int i; + + if (*buf == L'#') + buf++; + + component = 0; + i = convHexDigit(*buf++); + if (i < 0) + return FALSE; + component |= ((uint8_t) i) << 4; + i = convHexDigit(*buf++); + if (i < 0) + return FALSE; + component |= ((uint8_t) i); + *a = ((double) component) / 255; + + component = 0; + i = convHexDigit(*buf++); + if (i < 0) + return FALSE; + component |= ((uint8_t) i) << 4; + i = convHexDigit(*buf++); + if (i < 0) + return FALSE; + component |= ((uint8_t) i); + *r = ((double) component) / 255; + + component = 0; + i = convHexDigit(*buf++); + if (i < 0) + return FALSE; + component |= ((uint8_t) i) << 4; + i = convHexDigit(*buf++); + if (i < 0) + return FALSE; + component |= ((uint8_t) i); + *g = ((double) component) / 255; + + if (*buf == L'\0') { // #NNNNNN syntax + *b = *g; + *g = *r; + *r = *a; + *a = 1; + return TRUE; + } + + component = 0; + i = convHexDigit(*buf++); + if (i < 0) + return FALSE; + component |= ((uint8_t) i) << 4; + i = convHexDigit(*buf++); + if (i < 0) + return FALSE; + component |= ((uint8_t) i); + *b = ((double) component) / 255; + + return *buf == L'\0'; +} + +static void updateDouble(HWND hwnd, double d, HWND whichChanged) +{ + WCHAR *str; + + if (whichChanged == hwnd) + return; + str = ftoutf16(d); + setWindowText(hwnd, str); + uiprivFree(str); +} + +static void updateDialog(struct colorDialog *c, HWND whichChanged) +{ + double r, g, b; + uint8_t rb, gb, bb, ab; + WCHAR *str; + WCHAR hexbuf[16]; // more than enough + + c->updating = TRUE; + + updateDouble(c->editH, c->h, whichChanged); + updateDouble(c->editS, c->s, whichChanged); + updateDouble(c->editV, c->v, whichChanged); + + hsv2RGB(c->h, c->s, c->v, &r, &g, &b); + + updateDouble(c->editRDouble, r, whichChanged); + updateDouble(c->editGDouble, g, whichChanged); + updateDouble(c->editBDouble, b, whichChanged); + updateDouble(c->editADouble, c->a, whichChanged); + + rb = (uint8_t) (r * 255); + gb = (uint8_t) (g * 255); + bb = (uint8_t) (b * 255); + ab = (uint8_t) (c->a * 255); + + if (whichChanged != c->editRInt) { + str = itoutf16(rb); + setWindowText(c->editRInt, str); + uiprivFree(str); + } + if (whichChanged != c->editGInt) { + str = itoutf16(gb); + setWindowText(c->editGInt, str); + uiprivFree(str); + } + if (whichChanged != c->editBInt) { + str = itoutf16(bb); + setWindowText(c->editBInt, str); + uiprivFree(str); + } + if (whichChanged != c->editAInt) { + str = itoutf16(ab); + setWindowText(c->editAInt, str); + uiprivFree(str); + } + + if (whichChanged != c->editHex) { + rgba2Hex(rb, gb, bb, ab, hexbuf); + setWindowText(c->editHex, hexbuf); + } + + // TODO TRUE? + invalidateRect(c->svChooser, NULL, TRUE); + invalidateRect(c->hSlider, NULL, TRUE); + invalidateRect(c->preview, NULL, TRUE); + invalidateRect(c->opacitySlider, NULL, TRUE); + + c->updating = FALSE; +} + +// this imitates http://blogs.msdn.com/b/wpfsdk/archive/2006/10/26/uncommon-dialogs--font-chooser-and-color-picker-dialogs.aspx +static void drawGrid(ID2D1RenderTarget *rt, D2D1_RECT_F *fillRect) +{ + D2D1_SIZE_F size; + D2D1_PIXEL_FORMAT pformat; + ID2D1BitmapRenderTarget *brt; + D2D1_COLOR_F color; + D2D1_BRUSH_PROPERTIES bprop; + ID2D1SolidColorBrush *brush; + D2D1_RECT_F rect; + ID2D1Bitmap *bitmap; + D2D1_BITMAP_BRUSH_PROPERTIES bbp; + ID2D1BitmapBrush *bb; + HRESULT hr; + + // mind the divisions; they represent the fact the original uses a viewport + size.width = 100 / 10; + size.height = 100 / 10; + // yay more ABI bugs +#ifdef _MSC_VER + pformat = rt->GetPixelFormat(); +#else + { + typedef D2D1_PIXEL_FORMAT *(__stdcall ID2D1RenderTarget::* GetPixelFormatF)(D2D1_PIXEL_FORMAT *) const; + GetPixelFormatF gpf; + + gpf = (GetPixelFormatF) (&(rt->GetPixelFormat)); + (rt->*gpf)(&pformat); + } +#endif + hr = rt->CreateCompatibleRenderTarget(&size, NULL, + &pformat, D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS_NONE, + &brt); + if (hr != S_OK) + logHRESULT(L"error creating render target for grid", hr); + + brt->BeginDraw(); + + color.r = 1.0; + color.g = 1.0; + color.b = 1.0; + color.a = 1.0; + brt->Clear(&color); + + color = D2D1::ColorF(D2D1::ColorF::LightGray, 1.0); + ZeroMemory(&bprop, sizeof (D2D1_BRUSH_PROPERTIES)); + bprop.opacity = 1.0; + bprop.transform._11 = 1; + bprop.transform._22 = 1; + hr = brt->CreateSolidColorBrush(&color, &bprop, &brush); + if (hr != S_OK) + logHRESULT(L"error creating brush for grid", hr); + rect.left = 0; + rect.top = 0; + rect.right = 50 / 10; + rect.bottom = 50 / 10; + brt->FillRectangle(&rect, brush); + rect.left = 50 / 10; + rect.top = 50 / 10; + rect.right = 100 / 10; + rect.bottom = 100 / 10; + brt->FillRectangle(&rect, brush); + brush->Release(); + + hr = brt->EndDraw(NULL, NULL); + if (hr != S_OK) + logHRESULT(L"error finalizing render target for grid", hr); + hr = brt->GetBitmap(&bitmap); + if (hr != S_OK) + logHRESULT(L"error getting bitmap for grid", hr); + brt->Release(); + + ZeroMemory(&bbp, sizeof (D2D1_BITMAP_BRUSH_PROPERTIES)); + bbp.extendModeX = D2D1_EXTEND_MODE_WRAP; + bbp.extendModeY = D2D1_EXTEND_MODE_WRAP; + bbp.interpolationMode = D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR; + hr = rt->CreateBitmapBrush(bitmap, &bbp, &bprop, &bb); + if (hr != S_OK) + logHRESULT(L"error creating bitmap brush for grid", hr); + rt->FillRectangle(fillRect, bb); + bb->Release(); + bitmap->Release(); +} + +// this interesting approach comes from http://blogs.msdn.com/b/wpfsdk/archive/2006/10/26/uncommon-dialogs--font-chooser-and-color-picker-dialogs.aspx +static void drawSVChooser(struct colorDialog *c, ID2D1RenderTarget *rt) +{ + D2D1_SIZE_F size; + D2D1_RECT_F rect; + double rTop, gTop, bTop; + D2D1_GRADIENT_STOP stops[2]; + ID2D1GradientStopCollection *collection; + D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES lprop; + D2D1_BRUSH_PROPERTIES bprop; + ID2D1LinearGradientBrush *brush; + ID2D1LinearGradientBrush *opacity; + ID2D1Layer *layer; + D2D1_LAYER_PARAMETERS layerparams; + D2D1_ELLIPSE mparam; + D2D1_COLOR_F mcolor; + ID2D1SolidColorBrush *markerBrush; + HRESULT hr; + + size = realGetSize(rt); + rect.left = 0; + rect.top = 0; + rect.right = size.width; + rect.bottom = size.height; + + drawGrid(rt, &rect); + + // first, draw a vertical gradient from the current hue at max S/V to black + // the source example draws it upside down; let's do so too just to be safe + hsv2RGB(c->h, 1.0, 1.0, &rTop, &gTop, &bTop); + stops[0].position = 0; + stops[0].color.r = 0.0; + stops[0].color.g = 0.0; + stops[0].color.b = 0.0; + stops[0].color.a = 1.0; + stops[1].position = 1; + stops[1].color.r = rTop; + stops[1].color.g = gTop; + stops[1].color.b = bTop; + stops[1].color.a = 1.0; + hr = rt->CreateGradientStopCollection(stops, 2, + D2D1_GAMMA_2_2, D2D1_EXTEND_MODE_CLAMP, + &collection); + if (hr != S_OK) + logHRESULT(L"error making gradient stop collection for first gradient in SV chooser", hr); + ZeroMemory(&lprop, sizeof (D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES)); + lprop.startPoint.x = size.width / 2; + lprop.startPoint.y = size.height; + lprop.endPoint.x = size.width / 2; + lprop.endPoint.y = 0; + // TODO decide what to do about the duplication of this + ZeroMemory(&bprop, sizeof (D2D1_BRUSH_PROPERTIES)); + bprop.opacity = c->a; // note this part; we also use it below for the layer + bprop.transform._11 = 1; + bprop.transform._22 = 1; + hr = rt->CreateLinearGradientBrush(&lprop, &bprop, + collection, &brush); + if (hr != S_OK) + logHRESULT(L"error making gradient brush for first gradient in SV chooser", hr); + rt->FillRectangle(&rect, brush); + brush->Release(); + collection->Release(); + + // second, create an opacity mask for the third step: a horizontal gradientthat goes from opaque to translucent + stops[0].position = 0; + stops[0].color.r = 0.0; + stops[0].color.g = 0.0; + stops[0].color.b = 0.0; + stops[0].color.a = 1.0; + stops[1].position = 1; + stops[1].color.r = 0.0; + stops[1].color.g = 0.0; + stops[1].color.b = 0.0; + stops[1].color.a = 0.0; + hr = rt->CreateGradientStopCollection(stops, 2, + D2D1_GAMMA_2_2, D2D1_EXTEND_MODE_CLAMP, + &collection); + if (hr != S_OK) + logHRESULT(L"error making gradient stop collection for opacity mask gradient in SV chooser", hr); + ZeroMemory(&lprop, sizeof (D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES)); + lprop.startPoint.x = 0; + lprop.startPoint.y = size.height / 2; + lprop.endPoint.x = size.width; + lprop.endPoint.y = size.height / 2; + ZeroMemory(&bprop, sizeof (D2D1_BRUSH_PROPERTIES)); + bprop.opacity = 1.0; + bprop.transform._11 = 1; + bprop.transform._22 = 1; + hr = rt->CreateLinearGradientBrush(&lprop, &bprop, + collection, &opacity); + if (hr != S_OK) + logHRESULT(L"error making gradient brush for opacity mask gradient in SV chooser", hr); + collection->Release(); + + // finally, make a vertical gradient from white at the top to black at the bottom (right side up this time) and with the previous opacity mask + stops[0].position = 0; + stops[0].color.r = 1.0; + stops[0].color.g = 1.0; + stops[0].color.b = 1.0; + stops[0].color.a = 1.0; + stops[1].position = 1; + stops[1].color.r = 0.0; + stops[1].color.g = 0.0; + stops[1].color.b = 0.0; + stops[1].color.a = 1.0; + hr = rt->CreateGradientStopCollection(stops, 2, + D2D1_GAMMA_2_2, D2D1_EXTEND_MODE_CLAMP, + &collection); + if (hr != S_OK) + logHRESULT(L"error making gradient stop collection for second gradient in SV chooser", hr); + ZeroMemory(&lprop, sizeof (D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES)); + lprop.startPoint.x = size.width / 2; + lprop.startPoint.y = 0; + lprop.endPoint.x = size.width / 2; + lprop.endPoint.y = size.height; + ZeroMemory(&bprop, sizeof (D2D1_BRUSH_PROPERTIES)); + bprop.opacity = 1.0; + bprop.transform._11 = 1; + bprop.transform._22 = 1; + hr = rt->CreateLinearGradientBrush(&lprop, &bprop, + collection, &brush); + if (hr != S_OK) + logHRESULT(L"error making gradient brush for second gradient in SV chooser", hr); + // oh but wait we can't use FillRectangle() with an opacity mask + // and we can't use FillGeometry() with both an opacity mask and a non-bitmap + // layers it is! + hr = rt->CreateLayer(&size, &layer); + if (hr != S_OK) + logHRESULT(L"error making layer for second gradient in SV chooser", hr); + ZeroMemory(&layerparams, sizeof (D2D1_LAYER_PARAMETERS)); + layerparams.contentBounds = rect; + // TODO make sure these are right + layerparams.geometricMask = NULL; + layerparams.maskAntialiasMode = D2D1_ANTIALIAS_MODE_PER_PRIMITIVE; + layerparams.maskTransform._11 = 1; + layerparams.maskTransform._22 = 1; + layerparams.opacity = c->a; // here's the other use of c->a to note + layerparams.opacityBrush = opacity; + layerparams.layerOptions = D2D1_LAYER_OPTIONS_NONE; + rt->PushLayer(&layerparams, layer); + rt->FillRectangle(&rect, brush); + rt->PopLayer(); + layer->Release(); + brush->Release(); + collection->Release(); + opacity->Release(); + + // and now we just draw the marker + ZeroMemory(&mparam, sizeof (D2D1_ELLIPSE)); + mparam.point.x = c->s * size.width; + mparam.point.y = (1 - c->v) * size.height; + mparam.radiusX = 7; + mparam.radiusY = 7; + // TODO make the color contrast? + mcolor.r = 1.0; + mcolor.g = 1.0; + mcolor.b = 1.0; + mcolor.a = 1.0; + bprop.opacity = 1.0; // the marker should always be opaque + hr = rt->CreateSolidColorBrush(&mcolor, &bprop, &markerBrush); + if (hr != S_OK) + logHRESULT(L"error creating brush for SV chooser marker", hr); + rt->DrawEllipse(&mparam, markerBrush, 2, NULL); + markerBrush->Release(); +} + +static LRESULT CALLBACK svChooserSubProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData) +{ + ID2D1RenderTarget *rt; + struct colorDialog *c; + D2D1_POINT_2F *pos; + D2D1_SIZE_F *size; + + c = (struct colorDialog *) dwRefData; + switch (uMsg) { + case msgD2DScratchPaint: + rt = (ID2D1RenderTarget *) lParam; + drawSVChooser(c, rt); + return 0; + case msgD2DScratchLButtonDown: + pos = (D2D1_POINT_2F *) wParam; + size = (D2D1_SIZE_F *) lParam; + c->s = pos->x / size->width; + c->v = 1 - (pos->y / size->height); + updateDialog(c, NULL); + return 0; + case WM_NCDESTROY: + if (RemoveWindowSubclass(hwnd, svChooserSubProc, uIdSubclass) == FALSE) + logLastError(L"error removing color dialog SV chooser subclass"); + break; + } + return DefSubclassProc(hwnd, uMsg, wParam, lParam); +} + +static void drawArrow(ID2D1RenderTarget *rt, D2D1_POINT_2F center, double hypot) +{ + double leg; + D2D1_RECT_F rect; + D2D1_MATRIX_3X2_F oldtf, rotate; + D2D1_COLOR_F color; + D2D1_BRUSH_PROPERTIES bprop; + ID2D1SolidColorBrush *brush; + HRESULT hr; + + // to avoid needing a geometry, this will just be a rotated square + // compute the length of each side; the diagonal of the square is 2 * offset to gradient + // a^2 + a^2 = c^2 -> 2a^2 = c^2 + // a = sqrt(c^2/2) + hypot *= hypot; + hypot /= 2; + leg = sqrt(hypot); + rect.left = center.x - leg; + rect.top = center.y - leg; + rect.right = center.x + leg; + rect.bottom = center.y + leg; + + // now we need to rotate the render target 45° (either way works) about the center point + rt->GetTransform(&oldtf); + rotate = oldtf * D2D1::Matrix3x2F::Rotation(45, center); + rt->SetTransform(&rotate); + + // and draw + color.r = 0.0; + color.g = 0.0; + color.b = 0.0; + color.a = 1.0; + ZeroMemory(&bprop, sizeof (D2D1_BRUSH_PROPERTIES)); + bprop.opacity = 1.0; + bprop.transform._11 = 1; + bprop.transform._22 = 1; + hr = rt->CreateSolidColorBrush(&color, &bprop, &brush); + if (hr != S_OK) + logHRESULT(L"error creating brush for arrow", hr); + rt->FillRectangle(&rect, brush); + brush->Release(); + + // clean up + rt->SetTransform(&oldtf); +} + +// the gradient stuff also comes from http://blogs.msdn.com/b/wpfsdk/archive/2006/10/26/uncommon-dialogs--font-chooser-and-color-picker-dialogs.aspx +#define nStops (30) +#define degPerStop (360 / nStops) +#define stopIncr (1.0 / ((double) nStops)) + +static void drawHSlider(struct colorDialog *c, ID2D1RenderTarget *rt) +{ + D2D1_SIZE_F size; + D2D1_RECT_F rect; + D2D1_GRADIENT_STOP stops[nStops]; + double r, g, b; + int i; + double h; + ID2D1GradientStopCollection *collection; + D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES lprop; + D2D1_BRUSH_PROPERTIES bprop; + ID2D1LinearGradientBrush *brush; + double hypot; + D2D1_POINT_2F center; + HRESULT hr; + + size = realGetSize(rt); + rect.left = size.width / 6; // leftmost sixth for arrow + rect.top = 0; + rect.right = size.width; + rect.bottom = size.height; + + for (i = 0; i < nStops; i++) { + h = ((double) (i * degPerStop)) / 360.0; + if (i == (nStops - 1)) + h = 0; + hsv2RGB(h, 1.0, 1.0, &r, &g, &b); + stops[i].position = ((double) i) * stopIncr; + stops[i].color.r = r; + stops[i].color.g = g; + stops[i].color.b = b; + stops[i].color.a = 1.0; + } + // and pin the last one + stops[i - 1].position = 1.0; + + hr = rt->CreateGradientStopCollection(stops, nStops, + // note that in this case this gamma is explicitly specified by the original + D2D1_GAMMA_2_2, D2D1_EXTEND_MODE_CLAMP, + &collection); + if (hr != S_OK) + logHRESULT(L"error creating stop collection for H slider gradient", hr); + ZeroMemory(&lprop, sizeof (D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES)); + lprop.startPoint.x = (rect.right - rect.left) / 2; + lprop.startPoint.y = 0; + lprop.endPoint.x = (rect.right - rect.left) / 2; + lprop.endPoint.y = size.height; + ZeroMemory(&bprop, sizeof (D2D1_BRUSH_PROPERTIES)); + bprop.opacity = 1.0; + bprop.transform._11 = 1; + bprop.transform._22 = 1; + hr = rt->CreateLinearGradientBrush(&lprop, &bprop, + collection, &brush); + if (hr != S_OK) + logHRESULT(L"error creating gradient brush for H slider", hr); + rt->FillRectangle(&rect, brush); + brush->Release(); + collection->Release(); + + // now draw a black arrow + center.x = 0; + center.y = c->h * size.height; + hypot = rect.left; + drawArrow(rt, center, hypot); +} + +static LRESULT CALLBACK hSliderSubProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData) +{ + ID2D1RenderTarget *rt; + struct colorDialog *c; + D2D1_POINT_2F *pos; + D2D1_SIZE_F *size; + + c = (struct colorDialog *) dwRefData; + switch (uMsg) { + case msgD2DScratchPaint: + rt = (ID2D1RenderTarget *) lParam; + drawHSlider(c, rt); + return 0; + case msgD2DScratchLButtonDown: + pos = (D2D1_POINT_2F *) wParam; + size = (D2D1_SIZE_F *) lParam; + c->h = pos->y / size->height; + updateDialog(c, NULL); + return 0; + case WM_NCDESTROY: + if (RemoveWindowSubclass(hwnd, hSliderSubProc, uIdSubclass) == FALSE) + logLastError(L"error removing color dialog H slider subclass"); + break; + } + return DefSubclassProc(hwnd, uMsg, wParam, lParam); +} + +static void drawPreview(struct colorDialog *c, ID2D1RenderTarget *rt) +{ + D2D1_SIZE_F size; + D2D1_RECT_F rect; + double r, g, b; + D2D1_COLOR_F color; + D2D1_BRUSH_PROPERTIES bprop; + ID2D1SolidColorBrush *brush; + HRESULT hr; + + size = realGetSize(rt); + rect.left = 0; + rect.top = 0; + rect.right = size.width; + rect.bottom = size.height; + + drawGrid(rt, &rect); + + hsv2RGB(c->h, c->s, c->v, &r, &g, &b); + color.r = r; + color.g = g; + color.b = b; + color.a = c->a; + ZeroMemory(&bprop, sizeof (D2D1_BRUSH_PROPERTIES)); + bprop.opacity = 1.0; + bprop.transform._11 = 1; + bprop.transform._22 = 1; + hr = rt->CreateSolidColorBrush(&color, &bprop, &brush); + if (hr != S_OK) + logHRESULT(L"error creating brush for preview", hr); + rt->FillRectangle(&rect, brush); + brush->Release(); +} + +static LRESULT CALLBACK previewSubProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData) +{ + ID2D1RenderTarget *rt; + struct colorDialog *c; + + c = (struct colorDialog *) dwRefData; + switch (uMsg) { + case msgD2DScratchPaint: + rt = (ID2D1RenderTarget *) lParam; + drawPreview(c, rt); + return 0; + case WM_NCDESTROY: + if (RemoveWindowSubclass(hwnd, previewSubProc, uIdSubclass) == FALSE) + logLastError(L"error removing color dialog previewer subclass"); + break; + } + return DefSubclassProc(hwnd, uMsg, wParam, lParam); +} + +// once again, this is based on the Microsoft sample above +static void drawOpacitySlider(struct colorDialog *c, ID2D1RenderTarget *rt) +{ + D2D1_SIZE_F size; + D2D1_RECT_F rect; + D2D1_GRADIENT_STOP stops[2]; + ID2D1GradientStopCollection *collection; + D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES lprop; + D2D1_BRUSH_PROPERTIES bprop; + ID2D1LinearGradientBrush *brush; + double hypot; + D2D1_POINT_2F center; + HRESULT hr; + + size = realGetSize(rt); + rect.left = 0; + rect.top = 0; + rect.right = size.width; + rect.bottom = size.height * (5.0 / 6.0); // bottommost sixth for arrow + + drawGrid(rt, &rect); + + stops[0].position = 0.0; + stops[0].color.r = 0.0; + stops[0].color.g = 0.0; + stops[0].color.b = 0.0; + stops[0].color.a = 1.0; + stops[1].position = 1.0; + stops[1].color.r = 1.0; // this is the XAML color Transparent, as in the source + stops[1].color.g = 1.0; + stops[1].color.b = 1.0; + stops[1].color.a = 0.0; + hr = rt->CreateGradientStopCollection(stops, 2, + // note that in this case this gamma is explicitly specified by the original + D2D1_GAMMA_2_2, D2D1_EXTEND_MODE_CLAMP, + &collection); + if (hr != S_OK) + logHRESULT(L"error creating stop collection for opacity slider gradient", hr); + ZeroMemory(&lprop, sizeof (D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES)); + lprop.startPoint.x = 0; + lprop.startPoint.y = (rect.bottom - rect.top) / 2; + lprop.endPoint.x = size.width; + lprop.endPoint.y = (rect.bottom - rect.top) / 2; + ZeroMemory(&bprop, sizeof (D2D1_BRUSH_PROPERTIES)); + bprop.opacity = 1.0; + bprop.transform._11 = 1; + bprop.transform._22 = 1; + hr = rt->CreateLinearGradientBrush(&lprop, &bprop, + collection, &brush); + if (hr != S_OK) + logHRESULT(L"error creating gradient brush for opacity slider", hr); + rt->FillRectangle(&rect, brush); + brush->Release(); + collection->Release(); + + // now draw a black arrow + center.x = (1 - c->a) * size.width; + center.y = size.height; + hypot = size.height - rect.bottom; + drawArrow(rt, center, hypot); +} + +static LRESULT CALLBACK opacitySliderSubProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData) +{ + ID2D1RenderTarget *rt; + struct colorDialog *c; + D2D1_POINT_2F *pos; + D2D1_SIZE_F *size; + + c = (struct colorDialog *) dwRefData; + switch (uMsg) { + case msgD2DScratchPaint: + rt = (ID2D1RenderTarget *) lParam; + drawOpacitySlider(c, rt); + return 0; + case msgD2DScratchLButtonDown: + pos = (D2D1_POINT_2F *) wParam; + size = (D2D1_SIZE_F *) lParam; + c->a = 1 - (pos->x / size->width); + updateDialog(c, NULL); + return 0; + case WM_NCDESTROY: + if (RemoveWindowSubclass(hwnd, opacitySliderSubProc, uIdSubclass) == FALSE) + logLastError(L"error removing color dialog opacity slider subclass"); + break; + } + return DefSubclassProc(hwnd, uMsg, wParam, lParam); +} + +// TODO extract into d2dscratch.cpp, use in font dialog +HWND replaceWithD2DScratch(HWND parent, int id, SUBCLASSPROC subproc, void *data) +{ + HWND replace; + RECT r; + + replace = getDlgItem(parent, id); + uiWindowsEnsureGetWindowRect(replace, &r); + mapWindowRect(NULL, parent, &r); + uiWindowsEnsureDestroyWindow(replace); + return newD2DScratch(parent, &r, (HMENU) id, subproc, (DWORD_PTR) data); + // TODO preserve Z-order +} + +// a few issues: +// - some controls are positioned wrong; see http://stackoverflow.com/questions/37263267/why-are-some-of-my-controls-positioned-slightly-off-in-a-dialog-template-in-a-re +// - labels are too low; need to adjust them by the font's internal leading +// fixupControlPositions() and the following helper routines fix that for us + +static LONG offsetTo(HWND a, HWND b) +{ + RECT ra, rb; + + uiWindowsEnsureGetWindowRect(a, &ra); + uiWindowsEnsureGetWindowRect(b, &rb); + return rb.top - ra.bottom; +} + +static void moveWindowsUp(struct colorDialog *c, LONG by, ...) +{ + va_list ap; + HWND cur; + RECT r; + + va_start(ap, by); + for (;;) { + cur = va_arg(ap, HWND); + if (cur == NULL) + break; + uiWindowsEnsureGetWindowRect(cur, &r); + mapWindowRect(NULL, c->hwnd, &r); + r.top -= by; + r.bottom -= by; + // TODO this isn't technically during a resize + uiWindowsEnsureMoveWindowDuringResize(cur, + r.left, r.top, + r.right - r.left, r.bottom - r.top); + } + va_end(ap); +} + +static void fixupControlPositions(struct colorDialog *c) +{ + HWND labelH; + HWND labelS; + HWND labelV; + HWND labelR; + HWND labelG; + HWND labelB; + HWND labelA; + HWND labelHex; + LONG offset; + uiWindowsSizing sizing; + + labelH = getDlgItem(c->hwnd, rcHLabel); + labelS = getDlgItem(c->hwnd, rcSLabel); + labelV = getDlgItem(c->hwnd, rcVLabel); + labelR = getDlgItem(c->hwnd, rcRLabel); + labelG = getDlgItem(c->hwnd, rcGLabel); + labelB = getDlgItem(c->hwnd, rcBLabel); + labelA = getDlgItem(c->hwnd, rcALabel); + labelHex = getDlgItem(c->hwnd, rcHexLabel); + + offset = offsetTo(c->editH, c->editS); + moveWindowsUp(c, offset, + labelS, c->editS, + labelG, c->editGDouble, c->editGInt, + NULL); + offset = offsetTo(c->editS, c->editV); + moveWindowsUp(c, offset, + labelV, c->editV, + labelB, c->editBDouble, c->editBInt, + NULL); + offset = offsetTo(c->editBDouble, c->editADouble); + moveWindowsUp(c, offset, + labelA, c->editADouble, c->editAInt, + NULL); + + getSizing(c->hwnd, &sizing, (HFONT) SendMessageW(labelH, WM_GETFONT, 0, 0)); + offset = sizing.InternalLeading; + moveWindowsUp(c, offset, + labelH, labelS, labelV, + labelR, labelG, labelB, labelA, + labelHex, + NULL); +} + +static struct colorDialog *beginColorDialog(HWND hwnd, LPARAM lParam) +{ + struct colorDialog *c; + + c = uiprivNew(struct colorDialog); + c->hwnd = hwnd; + c->out = (struct colorDialogRGBA *) lParam; + // load initial values now + rgb2HSV(c->out->r, c->out->g, c->out->b, &(c->h), &(c->s), &(c->v)); + c->a = c->out->a; + + // TODO set up d2dscratches + + // TODO prefix all these with rcColor instead of just rc + c->editH = getDlgItem(c->hwnd, rcH); + c->editS = getDlgItem(c->hwnd, rcS); + c->editV = getDlgItem(c->hwnd, rcV); + c->editRDouble = getDlgItem(c->hwnd, rcRDouble); + c->editRInt = getDlgItem(c->hwnd, rcRInt); + c->editGDouble = getDlgItem(c->hwnd, rcGDouble); + c->editGInt = getDlgItem(c->hwnd, rcGInt); + c->editBDouble = getDlgItem(c->hwnd, rcBDouble); + c->editBInt = getDlgItem(c->hwnd, rcBInt); + c->editADouble = getDlgItem(c->hwnd, rcADouble); + c->editAInt = getDlgItem(c->hwnd, rcAInt); + c->editHex = getDlgItem(c->hwnd, rcHex); + + c->svChooser = replaceWithD2DScratch(c->hwnd, rcColorSVChooser, svChooserSubProc, c); + c->hSlider = replaceWithD2DScratch(c->hwnd, rcColorHSlider, hSliderSubProc, c); + c->preview = replaceWithD2DScratch(c->hwnd, rcPreview, previewSubProc, c); + c->opacitySlider = replaceWithD2DScratch(c->hwnd, rcOpacitySlider, opacitySliderSubProc, c); + + fixupControlPositions(c); + + // and get the ball rolling + updateDialog(c, NULL); + return c; +} + +static void endColorDialog(struct colorDialog *c, INT_PTR code) +{ + if (EndDialog(c->hwnd, code) == 0) + logLastError(L"error ending color dialog"); + uiprivFree(c); +} + +// TODO make this void on the font dialog too +static void tryFinishDialog(struct colorDialog *c, WPARAM wParam) +{ + // cancelling + if (LOWORD(wParam) != IDOK) { + endColorDialog(c, 1); + return; + } + + // OK + hsv2RGB(c->h, c->s, c->v, &(c->out->r), &(c->out->g), &(c->out->b)); + c->out->a = c->a; + endColorDialog(c, 2); +} + +static double editDouble(HWND hwnd) +{ + WCHAR *s; + double d; + + s = windowText(hwnd); + d = _wtof(s); + uiprivFree(s); + return d; +} + +static void hChanged(struct colorDialog *c) +{ + double h; + + h = editDouble(c->editH); + if (h < 0 || h >= 1.0) // note the >= + return; + c->h = h; + updateDialog(c, c->editH); +} + +static void sChanged(struct colorDialog *c) +{ + double s; + + s = editDouble(c->editS); + if (s < 0 || s > 1) + return; + c->s = s; + updateDialog(c, c->editS); +} + +static void vChanged(struct colorDialog *c) +{ + double v; + + v = editDouble(c->editV); + if (v < 0 || v > 1) + return; + c->v = v; + updateDialog(c, c->editV); +} + +static void rDoubleChanged(struct colorDialog *c) +{ + double r, g, b; + + hsv2RGB(c->h, c->s, c->v, &r, &g, &b); + r = editDouble(c->editRDouble); + if (r < 0 || r > 1) + return; + rgb2HSV(r, g, b, &(c->h), &(c->s), &(c->v)); + updateDialog(c, c->editRDouble); +} + +static void gDoubleChanged(struct colorDialog *c) +{ + double r, g, b; + + hsv2RGB(c->h, c->s, c->v, &r, &g, &b); + g = editDouble(c->editGDouble); + if (g < 0 || g > 1) + return; + rgb2HSV(r, g, b, &(c->h), &(c->s), &(c->v)); + updateDialog(c, c->editGDouble); +} + +static void bDoubleChanged(struct colorDialog *c) +{ + double r, g, b; + + hsv2RGB(c->h, c->s, c->v, &r, &g, &b); + b = editDouble(c->editBDouble); + if (b < 0 || b > 1) + return; + rgb2HSV(r, g, b, &(c->h), &(c->s), &(c->v)); + updateDialog(c, c->editBDouble); +} + +static void aDoubleChanged(struct colorDialog *c) +{ + double a; + + a = editDouble(c->editADouble); + if (a < 0 || a > 1) + return; + c->a = a; + updateDialog(c, c->editADouble); +} + +static int editInt(HWND hwnd) +{ + WCHAR *s; + int i; + + s = windowText(hwnd); + i = _wtoi(s); + uiprivFree(s); + return i; +} + +static void rIntChanged(struct colorDialog *c) +{ + double r, g, b; + int i; + + hsv2RGB(c->h, c->s, c->v, &r, &g, &b); + i = editInt(c->editRInt); + if (i < 0 || i > 255) + return; + r = ((double) i) / 255.0; + rgb2HSV(r, g, b, &(c->h), &(c->s), &(c->v)); + updateDialog(c, c->editRInt); +} + +static void gIntChanged(struct colorDialog *c) +{ + double r, g, b; + int i; + + hsv2RGB(c->h, c->s, c->v, &r, &g, &b); + i = editInt(c->editGInt); + if (i < 0 || i > 255) + return; + g = ((double) i) / 255.0; + rgb2HSV(r, g, b, &(c->h), &(c->s), &(c->v)); + updateDialog(c, c->editGInt); +} + +static void bIntChanged(struct colorDialog *c) +{ + double r, g, b; + int i; + + hsv2RGB(c->h, c->s, c->v, &r, &g, &b); + i = editInt(c->editBInt); + if (i < 0 || i > 255) + return; + b = ((double) i) / 255.0; + rgb2HSV(r, g, b, &(c->h), &(c->s), &(c->v)); + updateDialog(c, c->editBInt); +} + +static void aIntChanged(struct colorDialog *c) +{ + int a; + + a = editInt(c->editAInt); + if (a < 0 || a > 255) + return; + c->a = ((double) a) / 255; + updateDialog(c, c->editAInt); +} + +static void hexChanged(struct colorDialog *c) +{ + WCHAR *buf; + double r, g, b, a; + BOOL is; + + buf = windowText(c->editHex); + is = hex2RGBA(buf, &r, &g, &b, &a); + uiprivFree(buf); + if (!is) + return; + rgb2HSV(r, g, b, &(c->h), &(c->s), &(c->v)); + c->a = a; + updateDialog(c, c->editHex); +} + +// TODO change fontdialog to use this +// note that if we make this const, we get lots of weird compiler errors +static std::map changed = { + { rcH, hChanged }, + { rcS, sChanged }, + { rcV, vChanged }, + { rcRDouble, rDoubleChanged }, + { rcGDouble, gDoubleChanged }, + { rcBDouble, bDoubleChanged }, + { rcADouble, aDoubleChanged }, + { rcRInt, rIntChanged }, + { rcGInt, gIntChanged }, + { rcBInt, bIntChanged }, + { rcAInt, aIntChanged }, + { rcHex, hexChanged }, +}; + +static INT_PTR CALLBACK colorDialogDlgProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + struct colorDialog *c; + + c = (struct colorDialog *) GetWindowLongPtrW(hwnd, DWLP_USER); + if (c == NULL) { + if (uMsg == WM_INITDIALOG) { + c = beginColorDialog(hwnd, lParam); + SetWindowLongPtrW(hwnd, DWLP_USER, (LONG_PTR) c); + return TRUE; + } + return FALSE; + } + + switch (uMsg) { + case WM_COMMAND: + SetWindowLongPtrW(c->hwnd, DWLP_MSGRESULT, 0); // just in case + switch (LOWORD(wParam)) { + case IDOK: + case IDCANCEL: + if (HIWORD(wParam) != BN_CLICKED) + return FALSE; + tryFinishDialog(c, wParam); + return TRUE; + case rcH: + case rcS: + case rcV: + case rcRDouble: + case rcGDouble: + case rcBDouble: + case rcADouble: + case rcRInt: + case rcGInt: + case rcBInt: + case rcAInt: + case rcHex: + if (HIWORD(wParam) != EN_CHANGE) + return FALSE; + if (c->updating) // prevent infinite recursion during an update + return FALSE; + (*(changed[LOWORD(wParam)]))(c); + return TRUE; + } + return FALSE; + } + return FALSE; +} + +// because Windows doesn't really support resources in static libraries, we have to embed this directly; oh well +/* +rcColorDialog DIALOGEX 13, 54, 344, 209 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_3DLOOK +CAPTION "Color" +FONT 9, "Segoe UI" +BEGIN + // this size should be big enough to get at least 256x256 on font sizes >= 8 pt + CTEXT "AaBbYyZz", rcColorSVChooser, 7, 7, 195, 195, SS_NOPREFIX | SS_BLACKRECT + + // width is the suggested slider height since this is vertical + CTEXT "AaBbYyZz", rcColorHSlider, 206, 7, 15, 195, SS_NOPREFIX | SS_BLACKRECT + + LTEXT "Preview:", -1, 230, 7, 107, 9, SS_NOPREFIX + CTEXT "AaBbYyZz", rcPreview, 230, 16, 107, 20, SS_NOPREFIX | SS_BLACKRECT + + LTEXT "Opacity:", -1, 230, 45, 107, 9, SS_NOPREFIX + CTEXT "AaBbYyZz", rcOpacitySlider, 230, 54, 107, 15, SS_NOPREFIX | SS_BLACKRECT + + LTEXT "&H:", rcHLabel, 230, 81, 8, 8 + EDITTEXT rcH, 238, 78, 30, 14, ES_LEFT | ES_AUTOHSCROLL | WS_TABSTOP, WS_EX_CLIENTEDGE + LTEXT "&S:", rcSLabel, 230, 95, 8, 8 + EDITTEXT rcS, 238, 92, 30, 14, ES_LEFT | ES_AUTOHSCROLL | WS_TABSTOP, WS_EX_CLIENTEDGE + LTEXT "&V:", rcVLabel, 230, 109, 8, 8 + EDITTEXT rcV, 238, 106, 30, 14, ES_LEFT | ES_AUTOHSCROLL | WS_TABSTOP, WS_EX_CLIENTEDGE + + LTEXT "&R:", rcRLabel, 277, 81, 8, 8 + EDITTEXT rcRDouble, 285, 78, 30, 14, ES_LEFT | ES_AUTOHSCROLL | WS_TABSTOP, WS_EX_CLIENTEDGE + EDITTEXT rcRInt, 315, 78, 20, 14, ES_LEFT | ES_AUTOHSCROLL | ES_NUMBER | WS_TABSTOP, WS_EX_CLIENTEDGE + LTEXT "&G:", rcGLabel, 277, 95, 8, 8 + EDITTEXT rcGDouble, 285, 92, 30, 14, ES_LEFT | ES_AUTOHSCROLL | WS_TABSTOP, WS_EX_CLIENTEDGE + EDITTEXT rcGInt, 315, 92, 20, 14, ES_LEFT | ES_AUTOHSCROLL | ES_NUMBER | WS_TABSTOP, WS_EX_CLIENTEDGE + LTEXT "&B:", rcBLabel, 277, 109, 8, 8 + EDITTEXT rcBDouble, 285, 106, 30, 14, ES_LEFT | ES_AUTOHSCROLL | WS_TABSTOP, WS_EX_CLIENTEDGE + EDITTEXT rcBInt, 315, 106, 20, 14, ES_LEFT | ES_AUTOHSCROLL | ES_NUMBER | WS_TABSTOP, WS_EX_CLIENTEDGE + LTEXT "&A:", rcALabel, 277, 123, 8, 8 + EDITTEXT rcADouble, 285, 120, 30, 14, ES_LEFT | ES_AUTOHSCROLL | WS_TABSTOP, WS_EX_CLIENTEDGE + EDITTEXT rcAInt, 315, 120, 20, 14, ES_LEFT | ES_AUTOHSCROLL | ES_NUMBER | WS_TABSTOP, WS_EX_CLIENTEDGE + + LTEXT "He&x:", rcHexLabel, 269, 146, 16, 8 + EDITTEXT rcHex, 285, 143, 50, 14, ES_LEFT | ES_AUTOHSCROLL | WS_TABSTOP, WS_EX_CLIENTEDGE + + DEFPUSHBUTTON "OK", IDOK, 243, 188, 45, 14, WS_GROUP + PUSHBUTTON "Cancel", IDCANCEL, 292, 188, 45, 14, WS_GROUP +END +*/ +static const uint8_t data_rcColorDialog[] = { + 0x01, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xC4, 0x00, 0xC8, 0x80, + 0x1C, 0x00, 0x0D, 0x00, 0x36, 0x00, 0x58, 0x01, + 0xD1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x43, 0x00, + 0x6F, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x72, 0x00, + 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x53, 0x00, 0x65, 0x00, 0x67, 0x00, 0x6F, 0x00, + 0x65, 0x00, 0x20, 0x00, 0x55, 0x00, 0x49, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x85, 0x00, 0x02, 0x50, + 0x07, 0x00, 0x07, 0x00, 0xC3, 0x00, 0xC3, 0x00, + 0x4C, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x82, 0x00, + 0x41, 0x00, 0x61, 0x00, 0x42, 0x00, 0x62, 0x00, + 0x59, 0x00, 0x79, 0x00, 0x5A, 0x00, 0x7A, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x85, 0x00, 0x02, 0x50, + 0xCE, 0x00, 0x07, 0x00, 0x0F, 0x00, 0xC3, 0x00, + 0x4D, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x82, 0x00, + 0x41, 0x00, 0x61, 0x00, 0x42, 0x00, 0x62, 0x00, + 0x59, 0x00, 0x79, 0x00, 0x5A, 0x00, 0x7A, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x02, 0x50, + 0xE6, 0x00, 0x07, 0x00, 0x6B, 0x00, 0x09, 0x00, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x82, 0x00, + 0x50, 0x00, 0x72, 0x00, 0x65, 0x00, 0x76, 0x00, + 0x69, 0x00, 0x65, 0x00, 0x77, 0x00, 0x3A, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x85, 0x00, 0x02, 0x50, + 0xE6, 0x00, 0x10, 0x00, 0x6B, 0x00, 0x14, 0x00, + 0x4E, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x82, 0x00, + 0x41, 0x00, 0x61, 0x00, 0x42, 0x00, 0x62, 0x00, + 0x59, 0x00, 0x79, 0x00, 0x5A, 0x00, 0x7A, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x02, 0x50, + 0xE6, 0x00, 0x2D, 0x00, 0x6B, 0x00, 0x09, 0x00, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x82, 0x00, + 0x4F, 0x00, 0x70, 0x00, 0x61, 0x00, 0x63, 0x00, + 0x69, 0x00, 0x74, 0x00, 0x79, 0x00, 0x3A, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x85, 0x00, 0x02, 0x50, + 0xE6, 0x00, 0x36, 0x00, 0x6B, 0x00, 0x0F, 0x00, + 0x4F, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x82, 0x00, + 0x41, 0x00, 0x61, 0x00, 0x42, 0x00, 0x62, 0x00, + 0x59, 0x00, 0x79, 0x00, 0x5A, 0x00, 0x7A, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x50, + 0xE6, 0x00, 0x51, 0x00, 0x08, 0x00, 0x08, 0x00, + 0x5C, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x82, 0x00, + 0x26, 0x00, 0x48, 0x00, 0x3A, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x02, 0x00, 0x00, 0x80, 0x00, 0x81, 0x50, + 0xEE, 0x00, 0x4E, 0x00, 0x1E, 0x00, 0x0E, 0x00, + 0x50, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x81, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x50, + 0xE6, 0x00, 0x5F, 0x00, 0x08, 0x00, 0x08, 0x00, + 0x5D, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x82, 0x00, + 0x26, 0x00, 0x53, 0x00, 0x3A, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x02, 0x00, 0x00, 0x80, 0x00, 0x81, 0x50, + 0xEE, 0x00, 0x5C, 0x00, 0x1E, 0x00, 0x0E, 0x00, + 0x51, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x81, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x50, + 0xE6, 0x00, 0x6D, 0x00, 0x08, 0x00, 0x08, 0x00, + 0x5E, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x82, 0x00, + 0x26, 0x00, 0x56, 0x00, 0x3A, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x02, 0x00, 0x00, 0x80, 0x00, 0x81, 0x50, + 0xEE, 0x00, 0x6A, 0x00, 0x1E, 0x00, 0x0E, 0x00, + 0x52, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x81, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x50, + 0x15, 0x01, 0x51, 0x00, 0x08, 0x00, 0x08, 0x00, + 0x5F, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x82, 0x00, + 0x26, 0x00, 0x52, 0x00, 0x3A, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x02, 0x00, 0x00, 0x80, 0x00, 0x81, 0x50, + 0x1D, 0x01, 0x4E, 0x00, 0x1E, 0x00, 0x0E, 0x00, + 0x53, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x81, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x02, 0x00, 0x00, 0x80, 0x20, 0x81, 0x50, + 0x3B, 0x01, 0x4E, 0x00, 0x14, 0x00, 0x0E, 0x00, + 0x54, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x81, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x50, + 0x15, 0x01, 0x5F, 0x00, 0x08, 0x00, 0x08, 0x00, + 0x60, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x82, 0x00, + 0x26, 0x00, 0x47, 0x00, 0x3A, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x02, 0x00, 0x00, 0x80, 0x00, 0x81, 0x50, + 0x1D, 0x01, 0x5C, 0x00, 0x1E, 0x00, 0x0E, 0x00, + 0x55, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x81, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x02, 0x00, 0x00, 0x80, 0x20, 0x81, 0x50, + 0x3B, 0x01, 0x5C, 0x00, 0x14, 0x00, 0x0E, 0x00, + 0x56, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x81, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x50, + 0x15, 0x01, 0x6D, 0x00, 0x08, 0x00, 0x08, 0x00, + 0x61, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x82, 0x00, + 0x26, 0x00, 0x42, 0x00, 0x3A, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x02, 0x00, 0x00, 0x80, 0x00, 0x81, 0x50, + 0x1D, 0x01, 0x6A, 0x00, 0x1E, 0x00, 0x0E, 0x00, + 0x57, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x81, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x02, 0x00, 0x00, 0x80, 0x20, 0x81, 0x50, + 0x3B, 0x01, 0x6A, 0x00, 0x14, 0x00, 0x0E, 0x00, + 0x58, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x81, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x50, + 0x15, 0x01, 0x7B, 0x00, 0x08, 0x00, 0x08, 0x00, + 0x62, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x82, 0x00, + 0x26, 0x00, 0x41, 0x00, 0x3A, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x02, 0x00, 0x00, 0x80, 0x00, 0x81, 0x50, + 0x1D, 0x01, 0x78, 0x00, 0x1E, 0x00, 0x0E, 0x00, + 0x59, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x81, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x02, 0x00, 0x00, 0x80, 0x20, 0x81, 0x50, + 0x3B, 0x01, 0x78, 0x00, 0x14, 0x00, 0x0E, 0x00, + 0x5A, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x81, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x50, + 0x0D, 0x01, 0x92, 0x00, 0x10, 0x00, 0x08, 0x00, + 0x63, 0x04, 0x00, 0x00, 0xFF, 0xFF, 0x82, 0x00, + 0x48, 0x00, 0x65, 0x00, 0x26, 0x00, 0x78, 0x00, + 0x3A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, + 0x80, 0x00, 0x81, 0x50, 0x1D, 0x01, 0x8F, 0x00, + 0x32, 0x00, 0x0E, 0x00, 0x5B, 0x04, 0x00, 0x00, + 0xFF, 0xFF, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x03, 0x50, 0xF3, 0x00, 0xBC, 0x00, + 0x2D, 0x00, 0x0E, 0x00, 0x01, 0x00, 0x00, 0x00, + 0xFF, 0xFF, 0x80, 0x00, 0x4F, 0x00, 0x4B, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x50, + 0x24, 0x01, 0xBC, 0x00, 0x2D, 0x00, 0x0E, 0x00, + 0x02, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x80, 0x00, + 0x43, 0x00, 0x61, 0x00, 0x6E, 0x00, 0x63, 0x00, + 0x65, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, +}; +static_assert(ARRAYSIZE(data_rcColorDialog) == 1144, "wrong size for resource rcColorDialog"); + +BOOL showColorDialog(HWND parent, struct colorDialogRGBA *c) +{ + switch (DialogBoxIndirectParamW(hInstance, (const DLGTEMPLATE *) data_rcColorDialog, parent, colorDialogDlgProc, (LPARAM) c)) { + case 1: // cancel + return FALSE; + case 2: // ok + // make the compiler happy by putting the return after the switch + break; + default: + logLastError(L"error running color dialog"); + } + return TRUE; +} diff --git a/dep/libui/windows/combobox.cpp b/dep/libui/windows/combobox.cpp new file mode 100644 index 0000000..50f49dd --- /dev/null +++ b/dep/libui/windows/combobox.cpp @@ -0,0 +1,110 @@ +// 20 may 2015 +#include "uipriv_windows.hpp" + +// we as Common Controls 6 users don't need to worry about the height of comboboxes; see http://blogs.msdn.com/b/oldnewthing/archive/2006/03/10/548537.aspx + +struct uiCombobox { + uiWindowsControl c; + HWND hwnd; + void (*onSelected)(uiCombobox *, void *); + void *onSelectedData; +}; + +static BOOL onWM_COMMAND(uiControl *cc, HWND hwnd, WORD code, LRESULT *lResult) +{ + uiCombobox *c = uiCombobox(cc); + + if (code != CBN_SELCHANGE) + return FALSE; + (*(c->onSelected))(c, c->onSelectedData); + *lResult = 0; + return TRUE; +} + +void uiComboboxDestroy(uiControl *cc) +{ + uiCombobox *c = uiCombobox(cc); + + uiWindowsUnregisterWM_COMMANDHandler(c->hwnd); + uiWindowsEnsureDestroyWindow(c->hwnd); + uiFreeControl(uiControl(c)); +} + +uiWindowsControlAllDefaultsExceptDestroy(uiCombobox) + +// from http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing +#define comboboxWidth 107 /* this is actually the shorter progress bar width, but Microsoft only indicates as wide as necessary; LONGTERM */ +#define comboboxHeight 14 /* LONGTERM: is this too high? */ + +static void uiComboboxMinimumSize(uiWindowsControl *cc, int *width, int *height) +{ + uiCombobox *c = uiCombobox(cc); + uiWindowsSizing sizing; + int x, y; + + x = comboboxWidth; + y = comboboxHeight; + uiWindowsGetSizing(c->hwnd, &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, &x, &y); + *width = x; + *height = y; +} + +static void defaultOnSelected(uiCombobox *c, void *data) +{ + // do nothing +} + +void uiComboboxAppend(uiCombobox *c, const char *text) +{ + WCHAR *wtext; + LRESULT res; + + wtext = toUTF16(text); + res = SendMessageW(c->hwnd, CB_ADDSTRING, 0, (LPARAM) wtext); + if (res == (LRESULT) CB_ERR) + logLastError(L"error appending item to uiCombobox"); + else if (res == (LRESULT) CB_ERRSPACE) + logLastError(L"memory exhausted appending item to uiCombobox"); + uiprivFree(wtext); +} + +int uiComboboxSelected(uiCombobox *c) +{ + LRESULT n; + + n = SendMessage(c->hwnd, CB_GETCURSEL, 0, 0); + if (n == (LRESULT) CB_ERR) + return -1; + return n; +} + +void uiComboboxSetSelected(uiCombobox *c, int n) +{ + // TODO error check + SendMessageW(c->hwnd, CB_SETCURSEL, (WPARAM) n, 0); +} + +void uiComboboxOnSelected(uiCombobox *c, void (*f)(uiCombobox *c, void *data), void *data) +{ + c->onSelected = f; + c->onSelectedData = data; +} + +uiCombobox *uiNewCombobox(void) +{ + uiCombobox *c; + + uiWindowsNewControl(uiCombobox, c); + + c->hwnd = uiWindowsEnsureCreateControlHWND(WS_EX_CLIENTEDGE, + L"combobox", L"", + CBS_DROPDOWNLIST | WS_TABSTOP, + hInstance, NULL, + TRUE); + + uiWindowsRegisterWM_COMMANDHandler(c->hwnd, onWM_COMMAND, uiControl(c)); + uiComboboxOnSelected(c, defaultOnSelected, NULL); + + return c; +} diff --git a/dep/libui/windows/compilerver.hpp b/dep/libui/windows/compilerver.hpp new file mode 100644 index 0000000..c902ec2 --- /dev/null +++ b/dep/libui/windows/compilerver.hpp @@ -0,0 +1,95 @@ +// 9 june 2015 + +// Visual Studio (Microsoft's compilers) +// VS2013 is needed for va_copy(). +#ifdef _MSC_VER +#if _MSC_VER < 1800 +#error Visual Studio 2013 or higher is required to build libui. +#endif +#endif + +// LONGTERM MinGW + +// other compilers can be added here as necessary + +/* TODO this should not be necessary, but I don't know + +here's @bcampbell's original comment: +// sanity check - make sure wchar_t is 16 bits (the assumption on windows) +// (MinGW-w64 gcc does seem to define a 16bit wchar_t, but you never know. Other windows gcc ports might not) + +here's what I got when I tried to investigate on irc.oftc.net/#mingw-w64: +{ +[08:45:20] andlabs, the c++ standard requires `wchar_t` to be a distinct type. On Windows you can simply `static_assert(sizeof(wchar_t) == sizeof(unsigned short) && alignof(wchar_t) == alignof(unsigned short), "");` then reinterpret_cast those pointers. +[09:22:16] lh_mouse: yes; that was the point of my question =P but whether that static_assert is always true is another question I have, because again, windows embeds the idea of wchar_t being UTF-16 throughout the API, but when I went to look, I found that the clang developers had a very heated debate about it :S +[09:22:28] and I couldn't find any concrete information other than the msvc docs +[09:23:04] Since Windows 2000 the NT kernel uses UTF-16. +[09:23:50] If you don't care about Windows 9x you can just pretend non-UTF-16 APIs didn't exist. +[09:24:04] that's not what I meant +[09:24:06] Actually long long long ago Windows used UCS2. +[09:24:15] I meant whether sizeof(wchar_t) must necessarily equal sizeof(uint16_t) +[09:24:18] and likewise for alignof +[09:24:27] for all windows compilers +[09:24:29] anyway afk +[09:24:31] Yes. That is what the ABI says. +[09:24:40] is there a source for that I can point at other people +[09:24:45] the ABI != on Windows +[09:26:00] okay I really need to afk now but I was about to ask what you meant +[09:26:06] and by source I meant URL +[09:49:18] andlabs: Sent 17 minutes ago: Here is what Microsoft people describe `wchar_t`: https://docs.microsoft.com/en-us/cpp/cpp/char-wchar-t-char16-t-char32-t +[09:49:19] andlabs: Sent 17 minutes ago: It is quite guaranteed: 'In the Microsoft compiler, it represents a 16-bit wide character used to store Unicode encoded as UTF-16LE, the native character type on Windows operating systems.' +[09:50:08] andlabs, If you build for cygwin then `wchar_t` is probably `int`, just like what it is on Linux. +[09:51:00] yes but that's still a compiler-specific reference; I still don't know hwere Microsoft keeps its ABI documentation, and I'm still wondering what you mean by "the ABI != on Windows" with regards to establishing that guarantee +[09:52:13] This is already the ABI documentation: https://docs.microsoft.com/en-us/cpp/cpp/char-wchar-t-char16-t-char32-t +[09:52:15] Title: char, wchar_t, char16_t, char32_t | Microsoft Docs (at docs.microsoft.com) +[09:52:19] It describes C++ types, +[09:53:09] oh, ok +[09:54:47] I assume by the != statement you mean code that doesn't make any windows API calls can theoretically be compiled any which way, right +[09:55:05] yes. think about MSYS and Cygwin. +[09:55:21] They have 8-byte `long` and 4-byte `wchar_t`. +[09:57:37] right, except the code I'm trying to compile does use the Windows API, so that wouldn't apply to me +[09:57:43] I assume +[09:57:53] it wouldn't. +[09:59:12] On Windows it is sometimes necessary to assume specific ABI definition. For example, when a callback function returning a `DWORD` is to be declared in a header, in order to prevent `#include`'ing windows.h, you can just write `unsigned long` there. +[09:59:32] This is guaranteed to work on Windows. Linux will say otherwise. +[10:00:41] We all know `#include ` in a public header lets the genie out of the bottle, doesn't it? +[10:04:24] the zombie of win32_lean_and_mean lives forever +[10:04:53] of course now we have stdint.h and cstdint (which took longer because lolC++03) which helps stuff +[10:06:19] no `uint32_t` is `unsigned int` while `DWORD` is `unsigned long` hence they are incompatible. :( +[10:06:39] in what sense +[10:06:55] a `unsigned int *` cannot be converted to `unsigned long *` implicitly. +[10:07:41] the C standard says they are distinct pointer types and are not compatible, although `unsigned int` and `unsigned long` might have the same bit representation and alignment requirement. +[10:08:04] oh +[10:08:22] casting would indeed make code compile, but I tend to keep away from them unless necessary. +[10:08:24] wel yeah, but we haven't left the world of windows-specific code yet +[10:08:38] my point was more we don't need to use names like DWORD anymore +[10:08:51] of course it's easier to do so +[10:09:04] just use `uint32_t`. +[10:09:44] I just tested GCC 8 today and noticed they had added a warning for casting between incompatible function pointer types. +[10:10:10] So casting from `unsigned (*)(void)` to `unsigned long (*)(void)` now results in a warning. +[10:10:43] With `-Werror` it is a hard error. This can be worked around by casting the operand to an intermediate result of `intptr_t`. +[10:10:59] ... not so serious. +[10:11:42] oh good I wonder what else will break :D +[10:12:19] though the docs for dlsym() tell you what you should do instead for systems that use libdl (cast the address of your destination variable to void**) +[10:13:23] POSIX requires casting from `void *` to function pointers to work explicitly (see the docs for `dlsym()`). I am not sure what GCC people think about it. +[10:13:45] yes that's what I just said =P it avoids the problem entirely +[10:13:49] C++ says this is 'conditionally supported' and it is not a warning or error there. +[10:13:50] dlsym already returns void* +[10:14:13] something like dlsym would require an ABI guarantee on the matter anyway +[10:14:16] by definition +[10:14:32] Casting is evil. Double casting is double evil. So I keep myself away from them. +[10:15:03] sadly this is C (and C++) =P +[10:15:25] for `*-w64-mingw32` targets it is safe to cast between `unsigned short`, `wchar_t` and `char16_t`. +[10:15:33] as well as pointers to them. +[10:16:30] you just need to `static_assert` it, so something naughty will not compile. +[12:36:14] actually I didn't notice that last message until just now +[12:36:23] I was asking because I was sitting here thinking such a static_assert was unnecessary +} +clang debate: http://clang-developers.42468.n3.nabble.com/Is-that-getting-wchar-t-to-be-32bit-on-win32-a-good-idea-for-compatible-with-Unix-world-by-implement-td4045412.html + +so I'm not sure what is correct, but I do need to find out +*/ +#include +#if WCHAR_MAX > 0xFFFF +#error unexpected: wchar_t larger than 16-bit on a Windows ABI build; contact andlabs with your build setup information +#endif diff --git a/dep/libui/windows/container.cpp b/dep/libui/windows/container.cpp new file mode 100644 index 0000000..9ec1e28 --- /dev/null +++ b/dep/libui/windows/container.cpp @@ -0,0 +1,110 @@ +// 26 april 2015 +#include "uipriv_windows.hpp" + +// Code for the HWND of the following uiControls: +// - uiBox +// - uiRadioButtons +// - uiSpinbox +// - uiTab +// - uiForm +// - uiGrid + +struct containerInit { + uiWindowsControl *c; + void (*onResize)(uiWindowsControl *); +}; + +static LRESULT CALLBACK containerWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + RECT r; + HDC dc; + PAINTSTRUCT ps; + CREATESTRUCTW *cs = (CREATESTRUCTW *) lParam; + WINDOWPOS *wp = (WINDOWPOS *) lParam; + MINMAXINFO *mmi = (MINMAXINFO *) lParam; + struct containerInit *init; + uiWindowsControl *c; + void (*onResize)(uiWindowsControl *); + int minwid, minht; + LRESULT lResult; + + if (handleParentMessages(hwnd, uMsg, wParam, lParam, &lResult) != FALSE) + return lResult; + switch (uMsg) { + case WM_CREATE: + init = (struct containerInit *) (cs->lpCreateParams); + SetWindowLongPtrW(hwnd, GWLP_USERDATA, (LONG_PTR) (init->onResize)); + SetWindowLongPtrW(hwnd, 0, (LONG_PTR) (init->c)); + break; // defer to DefWindowProc() + case WM_WINDOWPOSCHANGED: + if ((wp->flags & SWP_NOSIZE) != 0) + break; // defer to DefWindowProc(); + onResize = (void (*)(uiWindowsControl *)) GetWindowLongPtrW(hwnd, GWLP_USERDATA); + c = (uiWindowsControl *) GetWindowLongPtrW(hwnd, 0); + (*(onResize))(c); + return 0; + case WM_GETMINMAXINFO: + lResult = DefWindowProcW(hwnd, uMsg, wParam, lParam); + c = (uiWindowsControl *) GetWindowLongPtrW(hwnd, 0); + uiWindowsControlMinimumSize(c, &minwid, &minht); + mmi->ptMinTrackSize.x = minwid; + mmi->ptMinTrackSize.y = minht; + return lResult; + case WM_PAINT: + dc = BeginPaint(hwnd, &ps); + if (dc == NULL) { + logLastError(L"error beginning container paint"); + // bail out; hope DefWindowProc() catches us + break; + } + r = ps.rcPaint; + paintContainerBackground(hwnd, dc, &r); + EndPaint(hwnd, &ps); + return 0; + // tab controls use this to draw the background of the tab area + case WM_PRINTCLIENT: + uiWindowsEnsureGetClientRect(hwnd, &r); + paintContainerBackground(hwnd, (HDC) wParam, &r); + return 0; + case WM_ERASEBKGND: + // avoid some flicker + // we draw the whole update area anyway + return 1; + } + return DefWindowProcW(hwnd, uMsg, wParam, lParam); +} + +ATOM initContainer(HICON hDefaultIcon, HCURSOR hDefaultCursor) +{ + WNDCLASSW wc; + + ZeroMemory(&wc, sizeof (WNDCLASSW)); + wc.lpszClassName = containerClass; + wc.lpfnWndProc = containerWndProc; + wc.hInstance = hInstance; + wc.hIcon = hDefaultIcon; + wc.hCursor = hDefaultCursor; + wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1); + wc.cbWndExtra = sizeof (void *); + return RegisterClassW(&wc); +} + +void uninitContainer(void) +{ + if (UnregisterClassW(containerClass, hInstance) == 0) + logLastError(L"error unregistering container window class"); +} + +HWND uiWindowsMakeContainer(uiWindowsControl *c, void (*onResize)(uiWindowsControl *)) +{ + struct containerInit init; + + // TODO onResize cannot be NULL + init.c = c; + init.onResize = onResize; + return uiWindowsEnsureCreateControlHWND(WS_EX_CONTROLPARENT, + containerClass, L"", + 0, + hInstance, (LPVOID) (&init), + FALSE); +} diff --git a/dep/libui/windows/control.cpp b/dep/libui/windows/control.cpp new file mode 100644 index 0000000..ce953cf --- /dev/null +++ b/dep/libui/windows/control.cpp @@ -0,0 +1,121 @@ +// 16 august 2015 +#include "uipriv_windows.hpp" + +void uiWindowsControlSyncEnableState(uiWindowsControl *c, int enabled) +{ + (*(c->SyncEnableState))(c, enabled); +} + +void uiWindowsControlSetParentHWND(uiWindowsControl *c, HWND parent) +{ + (*(c->SetParentHWND))(c, parent); +} + +void uiWindowsControlMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + (*(c->MinimumSize))(c, width, height); +} + +void uiWindowsControlMinimumSizeChanged(uiWindowsControl *c) +{ + (*(c->MinimumSizeChanged))(c); +} + +// TODO get rid of this +void uiWindowsControlLayoutRect(uiWindowsControl *c, RECT *r) +{ + (*(c->LayoutRect))(c, r); +} + +void uiWindowsControlAssignControlIDZOrder(uiWindowsControl *c, LONG_PTR *controlID, HWND *insertAfter) +{ + (*(c->AssignControlIDZOrder))(c, controlID, insertAfter); +} + +void uiWindowsControlChildVisibilityChanged(uiWindowsControl *c) +{ + (*(c->ChildVisibilityChanged))(c); +} + +HWND uiWindowsEnsureCreateControlHWND(DWORD dwExStyle, LPCWSTR lpClassName, LPCWSTR lpWindowName, DWORD dwStyle, HINSTANCE hInstance, LPVOID lpParam, BOOL useStandardControlFont) +{ + HWND hwnd; + + // don't let using the arrow keys in a uiRadioButtons leave the radio buttons + if ((dwStyle & WS_TABSTOP) != 0) + dwStyle |= WS_GROUP; + hwnd = CreateWindowExW(dwExStyle, + lpClassName, lpWindowName, + dwStyle | WS_CHILD | WS_VISIBLE, + 0, 0, + // use a nonzero initial size just in case some control breaks with a zero initial size + 100, 100, + utilWindow, NULL, hInstance, lpParam); + if (hwnd == NULL) { + logLastError(L"error creating window"); + // TODO return a decoy window + } + if (useStandardControlFont) + SendMessageW(hwnd, WM_SETFONT, (WPARAM) hMessageFont, (LPARAM) TRUE); + return hwnd; +} + +// choose a value distinct from uiWindowSignature +#define uiWindowsControlSignature 0x4D53576E + +uiWindowsControl *uiWindowsAllocControl(size_t n, uint32_t typesig, const char *typenamestr) +{ + return uiWindowsControl(uiAllocControl(n, uiWindowsControlSignature, typesig, typenamestr)); +} + +BOOL uiWindowsShouldStopSyncEnableState(uiWindowsControl *c, BOOL enabled) +{ + int ce; + + ce = uiControlEnabled(uiControl(c)); + // only stop if we're going from disabled back to enabled; don't stop under any other condition + // (if we stop when going from enabled to disabled then enabled children of a disabled control won't get disabled at the OS level) + if (!ce && enabled) + return TRUE; + return FALSE; +} + +void uiWindowsControlAssignSoleControlIDZOrder(uiWindowsControl *c) +{ + LONG_PTR controlID; + HWND insertAfter; + + controlID = 100; + insertAfter = NULL; + uiWindowsControlAssignControlIDZOrder(c, &controlID, &insertAfter); +} + +BOOL uiWindowsControlTooSmall(uiWindowsControl *c) +{ + RECT r; + int width, height; + + uiWindowsControlLayoutRect(c, &r); + uiWindowsControlMinimumSize(c, &width, &height); + if ((r.right - r.left) < width) + return TRUE; + if ((r.bottom - r.top) < height) + return TRUE; + return FALSE; +} + +void uiWindowsControlContinueMinimumSizeChanged(uiWindowsControl *c) +{ + uiControl *parent; + + parent = uiControlParent(uiControl(c)); + if (parent != NULL) + uiWindowsControlMinimumSizeChanged(uiWindowsControl(parent)); +} + +// TODO rename this nad the OS X this and hugging ones to NotifyChild +void uiWindowsControlNotifyVisibilityChanged(uiWindowsControl *c) +{ + // TODO we really need to figure this out; the duplication is a mess + uiWindowsControlContinueMinimumSizeChanged(c); +} diff --git a/dep/libui/windows/d2dscratch.cpp b/dep/libui/windows/d2dscratch.cpp new file mode 100644 index 0000000..6dc2ba5 --- /dev/null +++ b/dep/libui/windows/d2dscratch.cpp @@ -0,0 +1,166 @@ +// 17 april 2016 +#include "uipriv_windows.hpp" + +// The Direct2D scratch window is a utility for libui internal use to do quick things with Direct2D. +// To use, call newD2DScratch() passing in a subclass procedure. This subclass procedure should handle the msgD2DScratchPaint message, which has the following usage: +// - wParam - 0 +// - lParam - ID2D1RenderTarget * +// - lResult - 0 +// You can optionally also handle msgD2DScratchLButtonDown, which is sent when the left mouse button is either pressed for the first time or held while the mouse is moving. +// - wParam - position in DIPs, as D2D1_POINT_2F * +// - lParam - size of render target in DIPs, as D2D1_SIZE_F * +// - lResult - 0 +// Other messages can also be handled here. + +// TODO allow resize + +#define d2dScratchClass L"libui_d2dScratchClass" + +// TODO clip rect +static HRESULT d2dScratchDoPaint(HWND hwnd, ID2D1RenderTarget *rt) +{ + COLORREF bgcolorref; + D2D1_COLOR_F bgcolor; + + rt->BeginDraw(); + + // TODO only clear the clip area + // TODO clear with actual background brush + bgcolorref = GetSysColor(COLOR_BTNFACE); + bgcolor.r = ((float) GetRValue(bgcolorref)) / 255.0; + // due to utter apathy on Microsoft's part, GetGValue() does not work with MSVC's Run-Time Error Checks + // it has not worked since 2008 and they have *never* fixed it + // TODO now that -RTCc has just been deprecated entirely, should we switch back? + bgcolor.g = ((float) ((BYTE) ((bgcolorref & 0xFF00) >> 8))) / 255.0; + bgcolor.b = ((float) GetBValue(bgcolorref)) / 255.0; + bgcolor.a = 1.0; + rt->Clear(&bgcolor); + + SendMessageW(hwnd, msgD2DScratchPaint, 0, (LPARAM) rt); + + return rt->EndDraw(NULL, NULL); +} + +static void d2dScratchDoLButtonDown(HWND hwnd, ID2D1RenderTarget *rt, LPARAM lParam) +{ + double xpix, ypix; + FLOAT dpix, dpiy; + D2D1_POINT_2F pos; + D2D1_SIZE_F size; + + xpix = (double) GET_X_LPARAM(lParam); + ypix = (double) GET_Y_LPARAM(lParam); + // these are in pixels; we need points + // TODO separate the function from areautil.cpp? + rt->GetDpi(&dpix, &dpiy); + pos.x = (xpix * 96) / dpix; + pos.y = (ypix * 96) / dpiy; + + size = realGetSize(rt); + + SendMessageW(hwnd, msgD2DScratchLButtonDown, (WPARAM) (&pos), (LPARAM) (&size)); +} + +static LRESULT CALLBACK d2dScratchWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + LONG_PTR init; + ID2D1HwndRenderTarget *rt; + ID2D1DCRenderTarget *dcrt; + RECT client; + HRESULT hr; + + init = GetWindowLongPtrW(hwnd, 0); + if (!init) { + if (uMsg == WM_CREATE) + SetWindowLongPtrW(hwnd, 0, (LONG_PTR) TRUE); + return DefWindowProcW(hwnd, uMsg, wParam, lParam); + } + + rt = (ID2D1HwndRenderTarget *) GetWindowLongPtrW(hwnd, GWLP_USERDATA); + if (rt == NULL) { + rt = makeHWNDRenderTarget(hwnd); + SetWindowLongPtrW(hwnd, GWLP_USERDATA, (LONG_PTR) rt); + } + + switch (uMsg) { + case WM_DESTROY: + rt->Release(); + SetWindowLongPtrW(hwnd, 0, (LONG_PTR) FALSE); + break; + case WM_PAINT: + hr = d2dScratchDoPaint(hwnd, rt); + switch (hr) { + case S_OK: + if (ValidateRect(hwnd, NULL) == 0) + logLastError(L"error validating D2D scratch control rect"); + break; + case D2DERR_RECREATE_TARGET: + // DON'T validate the rect + // instead, simply drop the render target + // we'll get another WM_PAINT and make the render target again + // TODO would this require us to invalidate the entire client area? + rt->Release(); + SetWindowLongPtrW(hwnd, GWLP_USERDATA, (LONG_PTR) NULL); + break; + default: + logHRESULT(L"error drawing D2D scratch window", hr); + } + return 0; + case WM_PRINTCLIENT: + uiWindowsEnsureGetClientRect(hwnd, &client); + dcrt = makeHDCRenderTarget((HDC) wParam, &client); + hr = d2dScratchDoPaint(hwnd, dcrt); + if (hr != S_OK) + logHRESULT(L"error printing D2D scratch window client area", hr); + dcrt->Release(); + return 0; + case WM_LBUTTONDOWN: + d2dScratchDoLButtonDown(hwnd, rt, lParam); + return 0; + case WM_MOUSEMOVE: + // also send LButtonDowns when dragging + if ((wParam & MK_LBUTTON) != 0) + d2dScratchDoLButtonDown(hwnd, rt, lParam); + return 0; + } + return DefWindowProcW(hwnd, uMsg, wParam, lParam); +} + +ATOM registerD2DScratchClass(HICON hDefaultIcon, HCURSOR hDefaultCursor) +{ + WNDCLASSW wc; + + ZeroMemory(&wc, sizeof (WNDCLASSW)); + wc.lpszClassName = d2dScratchClass; + wc.lpfnWndProc = d2dScratchWndProc; + wc.hInstance = hInstance; + wc.hIcon = hDefaultIcon; + wc.hCursor = hDefaultCursor; + wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1); + wc.cbWndExtra = sizeof (LONG_PTR); // for the init status + return RegisterClassW(&wc); +} + +void unregisterD2DScratchClass(void) +{ + if (UnregisterClassW(d2dScratchClass, hInstance) == 0) + logLastError(L"error unregistering D2D scratch window class"); +} + +HWND newD2DScratch(HWND parent, RECT *rect, HMENU controlID, SUBCLASSPROC subclass, DWORD_PTR subclassData) +{ + HWND hwnd; + + hwnd = CreateWindowExW(0, + d2dScratchClass, L"", + WS_CHILD | WS_VISIBLE, + rect->left, rect->top, + rect->right - rect->left, rect->bottom - rect->top, + parent, controlID, hInstance, NULL); + if (hwnd == NULL) + // TODO return decoy window + logLastError(L"error creating D2D scratch window"); + if (SetWindowSubclass(hwnd, subclass, 0, subclassData) == FALSE) + logLastError(L"error subclassing D2D scratch window"); + return hwnd; +} diff --git a/dep/libui/windows/datetimepicker.cpp b/dep/libui/windows/datetimepicker.cpp new file mode 100644 index 0000000..32546cf --- /dev/null +++ b/dep/libui/windows/datetimepicker.cpp @@ -0,0 +1,261 @@ +// 22 may 2015 +#include "uipriv_windows.hpp" + +struct uiDateTimePicker { + uiWindowsControl c; + HWND hwnd; + void (*onChanged)(uiDateTimePicker *, void *); + void *onChangedData; +}; + +// utility functions + +#define GLI(what, buf, n) GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, what, buf, n) + +// The real date/time picker does a manual replacement of "yy" with "yyyy" for DTS_SHORTDATECENTURYFORMAT. +// Because we're also duplicating its functionality (see below), we have to do it too. +static WCHAR *expandYear(WCHAR *dts, int n) +{ + WCHAR *out; + WCHAR *p, *q; + int ny = 0; + + // allocate more than we need to be safe + out = (WCHAR *) uiprivAlloc((n * 3) * sizeof (WCHAR), "WCHAR[]"); + q = out; + for (p = dts; *p != L'\0'; p++) { + // first, if the current character is a y, increment the number of consecutive ys + // otherwise, stop counting, and if there were only two, add two more to make four + if (*p != L'y') { + if (ny == 2) { + *q++ = L'y'; + *q++ = L'y'; + } + ny = 0; + } else + ny++; + // next, handle quoted blocks + // we do this AFTER the above so yy'abc' becomes yyyy'abc' and not yy'abc'yy + // this handles the case of 'a''b' elegantly as well + if (*p == L'\'') { + // copy the opening quote + *q++ = *p; + // copy the contents + for (;;) { + p++; + if (*p == L'\'') + break; + if (*p == L'\0') + uiprivImplBug("unterminated quote in system-provided locale date string in expandYear()"); + *q++ = *p; + } + // and fall through to copy the closing quote + } + // copy the current character + *q++ = *p; + } + // handle trailing yy + if (ny == 2) { + *q++ = L'y'; + *q++ = L'y'; + } + *q++ = L'\0'; + return out; +} + +// Windows has no combined date/time prebuilt constant; we have to build the format string ourselves +// TODO use a default format if one fails +static void setDateTimeFormat(HWND hwnd) +{ + WCHAR *unexpandedDate, *date; + WCHAR *time; + WCHAR *datetime; + int ndate, ntime; + + ndate = GLI(LOCALE_SSHORTDATE, NULL, 0); + if (ndate == 0) + logLastError(L"error getting date string length"); + date = (WCHAR *) uiprivAlloc(ndate * sizeof (WCHAR), "WCHAR[]"); + if (GLI(LOCALE_SSHORTDATE, date, ndate) == 0) + logLastError(L"error geting date string"); + unexpandedDate = date; // so we can free it + date = expandYear(unexpandedDate, ndate); + uiprivFree(unexpandedDate); + + ntime = GLI(LOCALE_STIMEFORMAT, NULL, 0); + if (ndate == 0) + logLastError(L"error getting time string length"); + time = (WCHAR *) uiprivAlloc(ntime * sizeof (WCHAR), "WCHAR[]"); + if (GLI(LOCALE_STIMEFORMAT, time, ntime) == 0) + logLastError(L"error geting time string"); + + datetime = strf(L"%s %s", date, time); + if (SendMessageW(hwnd, DTM_SETFORMAT, 0, (LPARAM) datetime) == 0) + logLastError(L"error applying format string to date/time picker"); + + uiprivFree(datetime); + uiprivFree(time); + uiprivFree(date); +} + +// control implementation + +static void uiDateTimePickerDestroy(uiControl *c) +{ + uiDateTimePicker *d = uiDateTimePicker(c); + + uiWindowsUnregisterReceiveWM_WININICHANGE(d->hwnd); + uiWindowsUnregisterWM_NOTIFYHandler(d->hwnd); + uiWindowsEnsureDestroyWindow(d->hwnd); + uiFreeControl(uiControl(d)); +} + +uiWindowsControlAllDefaultsExceptDestroy(uiDateTimePicker) + +// the height returned from DTM_GETIDEALSIZE is unreliable; see http://stackoverflow.com/questions/30626549/what-is-the-proper-use-of-dtm-getidealsize-treating-the-returned-size-as-pixels +// from http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing +#define entryHeight 14 + +static void uiDateTimePickerMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + uiDateTimePicker *d = uiDateTimePicker(c); + SIZE s; + uiWindowsSizing sizing; + int y; + + s.cx = 0; + s.cy = 0; + SendMessageW(d->hwnd, DTM_GETIDEALSIZE, 0, (LPARAM) (&s)); + *width = s.cx; + + y = entryHeight; + uiWindowsGetSizing(d->hwnd, &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, NULL, &y); + *height = y; +} + +static BOOL onWM_NOTIFY(uiControl *c, HWND hwnd, NMHDR *nmhdr, LRESULT *lResult) +{ + uiDateTimePicker *d = uiDateTimePicker(c); + + if (nmhdr->code != DTN_DATETIMECHANGE) + return FALSE; + (*(d->onChanged))(d, d->onChangedData); + *lResult = 0; + return TRUE; +} + +static void fromSystemTime(SYSTEMTIME *systime, struct tm *time) +{ + ZeroMemory(time, sizeof (struct tm)); + time->tm_sec = systime->wSecond; + time->tm_min = systime->wMinute; + time->tm_hour = systime->wHour; + time->tm_mday = systime->wDay; + time->tm_mon = systime->wMonth - 1; + time->tm_year = systime->wYear - 1900; + time->tm_wday = systime->wDayOfWeek; + time->tm_isdst = -1; +} + +static void toSystemTime(const struct tm *time, SYSTEMTIME *systime) +{ + ZeroMemory(systime, sizeof (SYSTEMTIME)); + systime->wYear = time->tm_year + 1900; + systime->wMonth = time->tm_mon + 1; + systime->wDayOfWeek = time->tm_wday; + systime->wDay = time->tm_mday; + systime->wHour = time->tm_hour; + systime->wMinute = time->tm_min; + systime->wSecond = time->tm_sec; +} + +static void defaultOnChanged(uiDateTimePicker *d, void *data) +{ + // do nothing +} + +void uiDateTimePickerTime(uiDateTimePicker *d, struct tm *time) +{ + SYSTEMTIME systime; + + if (SendMessageW(d->hwnd, DTM_GETSYSTEMTIME, 0, (LPARAM) (&systime)) != GDT_VALID) + logLastError(L"error getting date and time"); + fromSystemTime(&systime, time); +} + +void uiDateTimePickerSetTime(uiDateTimePicker *d, const struct tm *time) +{ + SYSTEMTIME systime; + + toSystemTime(time, &systime); + if (SendMessageW(d->hwnd, DTM_SETSYSTEMTIME, GDT_VALID, (LPARAM) (&systime)) == 0) + logLastError(L"error setting date and time"); +} + +void uiDateTimePickerOnChanged(uiDateTimePicker *d, void (*f)(uiDateTimePicker *, void *), void *data) +{ + d->onChanged = f; + d->onChangedData = data; +} + +static uiDateTimePicker *finishNewDateTimePicker(DWORD style) +{ + uiDateTimePicker *d; + + uiWindowsNewControl(uiDateTimePicker, d); + + d->hwnd = uiWindowsEnsureCreateControlHWND(WS_EX_CLIENTEDGE, + DATETIMEPICK_CLASSW, L"", + style | WS_TABSTOP, + hInstance, NULL, + TRUE); + + // automatically update date/time format when user changes locale settings + // for the standard styles, this is in the date-time picker itself + // for our date/time mode, we do it in a subclass assigned in uiNewDateTimePicker() + uiWindowsRegisterReceiveWM_WININICHANGE(d->hwnd); + uiWindowsRegisterWM_NOTIFYHandler(d->hwnd, onWM_NOTIFY, uiControl(d)); + uiDateTimePickerOnChanged(d, defaultOnChanged, NULL); + + return d; +} + +static LRESULT CALLBACK datetimepickerSubProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData) +{ + switch (uMsg) { + case WM_WININICHANGE: + // we can optimize this by only doing it when the real date/time picker does it + // unfortunately, I don't know when that is :/ + // hopefully this won't hurt + setDateTimeFormat(hwnd); + return 0; + case WM_NCDESTROY: + if (RemoveWindowSubclass(hwnd, datetimepickerSubProc, uIdSubclass) == FALSE) + logLastError(L"error removing date-time picker locale change handling subclass"); + break; + } + return DefSubclassProc(hwnd, uMsg, wParam, lParam); +} + +uiDateTimePicker *uiNewDateTimePicker(void) +{ + uiDateTimePicker *d; + + d = finishNewDateTimePicker(0); + setDateTimeFormat(d->hwnd); + if (SetWindowSubclass(d->hwnd, datetimepickerSubProc, 0, (DWORD_PTR) d) == FALSE) + logLastError(L"error subclassing date-time-picker to assist in locale change handling"); + // TODO set a suitable default in this case + return d; +} + +uiDateTimePicker *uiNewDatePicker(void) +{ + return finishNewDateTimePicker(DTS_SHORTDATECENTURYFORMAT); +} + +uiDateTimePicker *uiNewTimePicker(void) +{ + return finishNewDateTimePicker(DTS_TIMEFORMAT); +} diff --git a/dep/libui/windows/debug.cpp b/dep/libui/windows/debug.cpp new file mode 100644 index 0000000..107b53a --- /dev/null +++ b/dep/libui/windows/debug.cpp @@ -0,0 +1,84 @@ +// 25 february 2015 +#include "uipriv_windows.hpp" + +// LONGTERM disable logging and stopping on no-debug builds + +static void printDebug(const WCHAR *msg) +{ + OutputDebugStringW(msg); +} + +HRESULT _logLastError(debugargs, const WCHAR *s) +{ + DWORD le; + WCHAR *msg; + WCHAR *formatted; + BOOL useFormatted; + + le = GetLastError(); + + useFormatted = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, le, 0, (LPWSTR) (&formatted), 0, NULL) != 0; + if (!useFormatted) + formatted = (WCHAR *) L"\n"; // TODO + msg = strf(L"[libui] %s:%s:%s() %s: GetLastError() == %I32u %s", + file, line, func, + s, le, formatted); + if (useFormatted) + LocalFree(formatted); // ignore error + printDebug(msg); + uiprivFree(msg); + DebugBreak(); + + SetLastError(le); + // a function does not have to set a last error + // if the last error we get is actually 0, then HRESULT_FROM_WIN32(0) will return S_OK (0 cast to an HRESULT, since 0 <= 0), which we don't want + // prevent this by returning E_FAIL + if (le == 0) + return E_FAIL; + return HRESULT_FROM_WIN32(le); +} + +HRESULT _logHRESULT(debugargs, const WCHAR *s, HRESULT hr) +{ + WCHAR *msg; + WCHAR *formatted; + BOOL useFormatted; + + useFormatted = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, hr, 0, (LPWSTR) (&formatted), 0, NULL) != 0; + if (!useFormatted) + formatted = (WCHAR *) L"\n"; // TODO + msg = strf(L"[libui] %s:%s:%s() %s: HRESULT == 0x%08I32X %s", + file, line, func, + s, hr, formatted); + if (useFormatted) + LocalFree(formatted); // ignore error + printDebug(msg); + uiprivFree(msg); + DebugBreak(); + + return hr; +} + +void uiprivRealBug(const char *file, const char *line, const char *func, const char *prefix, const char *format, va_list ap) +{ + va_list ap2; + char *msg; + size_t n; + WCHAR *final; + + va_copy(ap2, ap); + n = _vscprintf(format, ap2); + va_end(ap2); + n++; // terminating '\0' + + msg = (char *) uiprivAlloc(n * sizeof (char), "char[]"); + // includes terminating '\0' according to example in https://msdn.microsoft.com/en-us/library/xa1a1a6z.aspx + vsprintf_s(msg, n, format, ap); + + final = strf(L"[libui] %hs:%hs:%hs() %hs%hs\n", file, line, func, prefix, msg); + uiprivFree(msg); + printDebug(final); + uiprivFree(final); + + DebugBreak(); +} diff --git a/dep/libui/windows/draw.cpp b/dep/libui/windows/draw.cpp new file mode 100644 index 0000000..a5e5033 --- /dev/null +++ b/dep/libui/windows/draw.cpp @@ -0,0 +1,511 @@ +// 7 september 2015 +#include "uipriv_windows.hpp" +#include "draw.hpp" + +ID2D1Factory *d2dfactory = NULL; + +HRESULT initDraw(void) +{ + D2D1_FACTORY_OPTIONS opts; + + ZeroMemory(&opts, sizeof (D2D1_FACTORY_OPTIONS)); + // TODO make this an option + opts.debugLevel = D2D1_DEBUG_LEVEL_NONE; + return D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, + IID_ID2D1Factory, + &opts, + (void **) (&d2dfactory)); +} + +void uninitDraw(void) +{ + d2dfactory->Release(); +} + +ID2D1HwndRenderTarget *makeHWNDRenderTarget(HWND hwnd) +{ + D2D1_RENDER_TARGET_PROPERTIES props; + D2D1_HWND_RENDER_TARGET_PROPERTIES hprops; + HDC dc; + RECT r; + ID2D1HwndRenderTarget *rt; + HRESULT hr; + + // we need a DC for the DPI + // we *could* just use the screen DPI but why when we have a window handle and its DC has a DPI + dc = GetDC(hwnd); + if (dc == NULL) + logLastError(L"error getting DC to find DPI"); + + ZeroMemory(&props, sizeof (D2D1_RENDER_TARGET_PROPERTIES)); + props.type = D2D1_RENDER_TARGET_TYPE_DEFAULT; + props.pixelFormat.format = DXGI_FORMAT_UNKNOWN; + props.pixelFormat.alphaMode = D2D1_ALPHA_MODE_UNKNOWN; + props.dpiX = GetDeviceCaps(dc, LOGPIXELSX); + props.dpiY = GetDeviceCaps(dc, LOGPIXELSY); + props.usage = D2D1_RENDER_TARGET_USAGE_NONE; + props.minLevel = D2D1_FEATURE_LEVEL_DEFAULT; + + if (ReleaseDC(hwnd, dc) == 0) + logLastError(L"error releasing DC for finding DPI"); + + uiWindowsEnsureGetClientRect(hwnd, &r); + + ZeroMemory(&hprops, sizeof (D2D1_HWND_RENDER_TARGET_PROPERTIES)); + hprops.hwnd = hwnd; + hprops.pixelSize.width = r.right - r.left; + hprops.pixelSize.height = r.bottom - r.top; + // according to Rick Brewster, some drivers will misbehave if we don't specify this (see http://stackoverflow.com/a/33222983/3408572) + hprops.presentOptions = D2D1_PRESENT_OPTIONS_RETAIN_CONTENTS; + + hr = d2dfactory->CreateHwndRenderTarget( + &props, + &hprops, + &rt); + if (hr != S_OK) + logHRESULT(L"error creating HWND render target", hr); + return rt; +} + +ID2D1DCRenderTarget *makeHDCRenderTarget(HDC dc, RECT *r) +{ + D2D1_RENDER_TARGET_PROPERTIES props; + ID2D1DCRenderTarget *rt; + HRESULT hr; + + ZeroMemory(&props, sizeof (D2D1_RENDER_TARGET_PROPERTIES)); + props.type = D2D1_RENDER_TARGET_TYPE_DEFAULT; + props.pixelFormat.format = DXGI_FORMAT_B8G8R8A8_UNORM; + props.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED; + props.dpiX = GetDeviceCaps(dc, LOGPIXELSX); + props.dpiY = GetDeviceCaps(dc, LOGPIXELSY); + props.usage = D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE; + props.minLevel = D2D1_FEATURE_LEVEL_DEFAULT; + + hr = d2dfactory->CreateDCRenderTarget(&props, &rt); + if (hr != S_OK) + logHRESULT(L"error creating DC render target", hr); + hr = rt->BindDC(dc, r); + if (hr != S_OK) + logHRESULT(L"error binding DC to DC render target", hr); + return rt; +} + +static void resetTarget(ID2D1RenderTarget *rt) +{ + D2D1_MATRIX_3X2_F dm; + + // transformations persist + // reset to the identity matrix + ZeroMemory(&dm, sizeof (D2D1_MATRIX_3X2_F)); + dm._11 = 1; + dm._22 = 1; + rt->SetTransform(&dm); +} + +uiDrawContext *newContext(ID2D1RenderTarget *rt) +{ + uiDrawContext *c; + + c = uiprivNew(uiDrawContext); + c->rt = rt; + c->states = new std::vector; + resetTarget(c->rt); + return c; +} + +void freeContext(uiDrawContext *c) +{ + if (c->currentClip != NULL) + c->currentClip->Release(); + if (c->states->size() != 0) + // TODO do this on other platforms + uiprivUserBug("You did not balance uiDrawSave() and uiDrawRestore() calls."); + delete c->states; + uiprivFree(c); +} + +static ID2D1Brush *makeSolidBrush(uiDrawBrush *b, ID2D1RenderTarget *rt, D2D1_BRUSH_PROPERTIES *props) +{ + D2D1_COLOR_F color; + ID2D1SolidColorBrush *brush; + HRESULT hr; + + color.r = b->R; + color.g = b->G; + color.b = b->B; + color.a = b->A; + + hr = rt->CreateSolidColorBrush( + &color, + props, + &brush); + if (hr != S_OK) + logHRESULT(L"error creating solid brush", hr); + return brush; +} + +static ID2D1GradientStopCollection *mkstops(uiDrawBrush *b, ID2D1RenderTarget *rt) +{ + ID2D1GradientStopCollection *s; + D2D1_GRADIENT_STOP *stops; + size_t i; + HRESULT hr; + + stops = (D2D1_GRADIENT_STOP *) uiprivAlloc(b->NumStops * sizeof (D2D1_GRADIENT_STOP), "D2D1_GRADIENT_STOP[]"); + for (i = 0; i < b->NumStops; i++) { + stops[i].position = b->Stops[i].Pos; + stops[i].color.r = b->Stops[i].R; + stops[i].color.g = b->Stops[i].G; + stops[i].color.b = b->Stops[i].B; + stops[i].color.a = b->Stops[i].A; + } + + hr = rt->CreateGradientStopCollection( + stops, + b->NumStops, + D2D1_GAMMA_2_2, // this is the default for the C++-only overload of ID2D1RenderTarget::GradientStopCollection() + D2D1_EXTEND_MODE_CLAMP, + &s); + if (hr != S_OK) + logHRESULT(L"error creating stop collection", hr); + + uiprivFree(stops); + return s; +} + +static ID2D1Brush *makeLinearBrush(uiDrawBrush *b, ID2D1RenderTarget *rt, D2D1_BRUSH_PROPERTIES *props) +{ + ID2D1LinearGradientBrush *brush; + D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES gprops; + ID2D1GradientStopCollection *stops; + HRESULT hr; + + ZeroMemory(&gprops, sizeof (D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES)); + gprops.startPoint.x = b->X0; + gprops.startPoint.y = b->Y0; + gprops.endPoint.x = b->X1; + gprops.endPoint.y = b->Y1; + + stops = mkstops(b, rt); + + hr = rt->CreateLinearGradientBrush( + &gprops, + props, + stops, + &brush); + if (hr != S_OK) + logHRESULT(L"error creating gradient brush", hr); + + // the example at https://msdn.microsoft.com/en-us/library/windows/desktop/dd756682%28v=vs.85%29.aspx says this is safe to do now + stops->Release(); + return brush; +} + +static ID2D1Brush *makeRadialBrush(uiDrawBrush *b, ID2D1RenderTarget *rt, D2D1_BRUSH_PROPERTIES *props) +{ + ID2D1RadialGradientBrush *brush; + D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES gprops; + ID2D1GradientStopCollection *stops; + HRESULT hr; + + ZeroMemory(&gprops, sizeof (D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES)); + gprops.gradientOriginOffset.x = b->X0 - b->X1; + gprops.gradientOriginOffset.y = b->Y0 - b->Y1; + gprops.center.x = b->X1; + gprops.center.y = b->Y1; + gprops.radiusX = b->OuterRadius; + gprops.radiusY = b->OuterRadius; + + stops = mkstops(b, rt); + + hr = rt->CreateRadialGradientBrush( + &gprops, + props, + stops, + &brush); + if (hr != S_OK) + logHRESULT(L"error creating gradient brush", hr); + + stops->Release(); + return brush; +} + +static ID2D1Brush *makeBrush(uiDrawBrush *b, ID2D1RenderTarget *rt) +{ + D2D1_BRUSH_PROPERTIES props; + + ZeroMemory(&props, sizeof (D2D1_BRUSH_PROPERTIES)); + props.opacity = 1.0; + // identity matrix + props.transform._11 = 1; + props.transform._22 = 1; + + switch (b->Type) { + case uiDrawBrushTypeSolid: + return makeSolidBrush(b, rt, &props); + case uiDrawBrushTypeLinearGradient: + return makeLinearBrush(b, rt, &props); + case uiDrawBrushTypeRadialGradient: + return makeRadialBrush(b, rt, &props); +// case uiDrawBrushTypeImage: +// TODO + } + + // TODO do this on all platforms + uiprivUserBug("Invalid brush type %d given to drawing operation.", b->Type); + // TODO dummy brush? + return NULL; // make compiler happy +} + +// how clipping works: +// every fill and stroke is done on a temporary layer with the clip geometry applied to it +// this is really the only way to clip in Direct2D that doesn't involve opacity images +// reference counting: +// - initially the clip is NULL, which means do not use a layer +// - the first time uiDrawClip() is called, we take a reference on the path passed in (this is also why uiPathEnd() is needed) +// - every successive time, we create a new PathGeometry and merge the current clip with the new path, releasing the reference we took earlier and taking a reference to the new one +// - in Save, we take another reference; in Restore we drop the refernece to the existing path geometry and transfer that saved ref to the new path geometry over to the context +// uiDrawFreePath() doesn't destroy the path geometry, it just drops the reference count, so a clip can exist independent of its path + +static ID2D1Layer *applyClip(uiDrawContext *c) +{ + ID2D1Layer *layer; + D2D1_LAYER_PARAMETERS params; + HRESULT hr; + + // if no clip, don't do anything + if (c->currentClip == NULL) + return NULL; + + // create a layer for clipping + // we have to explicitly make the layer because we're still targeting Windows 7 + hr = c->rt->CreateLayer(NULL, &layer); + if (hr != S_OK) + logHRESULT(L"error creating clip layer", hr); + + // apply it as the clip + ZeroMemory(¶ms, sizeof (D2D1_LAYER_PARAMETERS)); + // this is the equivalent of InfiniteRect() in d2d1helper.h + params.contentBounds.left = -FLT_MAX; + params.contentBounds.top = -FLT_MAX; + params.contentBounds.right = FLT_MAX; + params.contentBounds.bottom = FLT_MAX; + params.geometricMask = (ID2D1Geometry *) (c->currentClip); + // TODO is this correct? + params.maskAntialiasMode = c->rt->GetAntialiasMode(); + // identity matrix + params.maskTransform._11 = 1; + params.maskTransform._22 = 1; + params.opacity = 1.0; + params.opacityBrush = NULL; + params.layerOptions = D2D1_LAYER_OPTIONS_NONE; + // TODO is this correct? + if (c->rt->GetTextAntialiasMode() == D2D1_TEXT_ANTIALIAS_MODE_CLEARTYPE) + params.layerOptions = D2D1_LAYER_OPTIONS_INITIALIZE_FOR_CLEARTYPE; + c->rt->PushLayer(¶ms, layer); + + // return the layer so it can be freed later + return layer; +} + +static void unapplyClip(uiDrawContext *c, ID2D1Layer *layer) +{ + if (layer == NULL) + return; + c->rt->PopLayer(); + layer->Release(); +} + +void uiDrawStroke(uiDrawContext *c, uiDrawPath *p, uiDrawBrush *b, uiDrawStrokeParams *sp) +{ + ID2D1Brush *brush; + ID2D1StrokeStyle *style; + D2D1_STROKE_STYLE_PROPERTIES dsp; + FLOAT *dashes; + size_t i; + ID2D1Layer *cliplayer; + HRESULT hr; + + brush = makeBrush(b, c->rt); + + ZeroMemory(&dsp, sizeof (D2D1_STROKE_STYLE_PROPERTIES)); + switch (sp->Cap) { + case uiDrawLineCapFlat: + dsp.startCap = D2D1_CAP_STYLE_FLAT; + dsp.endCap = D2D1_CAP_STYLE_FLAT; + dsp.dashCap = D2D1_CAP_STYLE_FLAT; + break; + case uiDrawLineCapRound: + dsp.startCap = D2D1_CAP_STYLE_ROUND; + dsp.endCap = D2D1_CAP_STYLE_ROUND; + dsp.dashCap = D2D1_CAP_STYLE_ROUND; + break; + case uiDrawLineCapSquare: + dsp.startCap = D2D1_CAP_STYLE_SQUARE; + dsp.endCap = D2D1_CAP_STYLE_SQUARE; + dsp.dashCap = D2D1_CAP_STYLE_SQUARE; + break; + } + switch (sp->Join) { + case uiDrawLineJoinMiter: + dsp.lineJoin = D2D1_LINE_JOIN_MITER_OR_BEVEL; + dsp.miterLimit = sp->MiterLimit; + break; + case uiDrawLineJoinRound: + dsp.lineJoin = D2D1_LINE_JOIN_ROUND; + break; + case uiDrawLineJoinBevel: + dsp.lineJoin = D2D1_LINE_JOIN_BEVEL; + break; + } + dsp.dashStyle = D2D1_DASH_STYLE_SOLID; + dashes = NULL; + // note that dash widths and the dash phase are scaled up by the thickness by Direct2D + // TODO be sure to formally document this + if (sp->NumDashes != 0) { + dsp.dashStyle = D2D1_DASH_STYLE_CUSTOM; + dashes = (FLOAT *) uiprivAlloc(sp->NumDashes * sizeof (FLOAT), "FLOAT[]"); + for (i = 0; i < sp->NumDashes; i++) + dashes[i] = sp->Dashes[i] / sp->Thickness; + } + dsp.dashOffset = sp->DashPhase / sp->Thickness; + hr = d2dfactory->CreateStrokeStyle( + &dsp, + dashes, + sp->NumDashes, + &style); + if (hr != S_OK) + logHRESULT(L"error creating stroke style", hr); + if (sp->NumDashes != 0) + uiprivFree(dashes); + + cliplayer = applyClip(c); + c->rt->DrawGeometry( + pathGeometry(p), + brush, + sp->Thickness, + style); + unapplyClip(c, cliplayer); + + style->Release(); + brush->Release(); +} + +void uiDrawFill(uiDrawContext *c, uiDrawPath *p, uiDrawBrush *b) +{ + ID2D1Brush *brush; + ID2D1Layer *cliplayer; + + brush = makeBrush(b, c->rt); + cliplayer = applyClip(c); + c->rt->FillGeometry( + pathGeometry(p), + brush, + NULL); + unapplyClip(c, cliplayer); + brush->Release(); +} + +void uiDrawTransform(uiDrawContext *c, uiDrawMatrix *m) +{ + D2D1_MATRIX_3X2_F dm, cur; + + c->rt->GetTransform(&cur); + m2d(m, &dm); + // you would think we have to do already * m, right? + // WRONG! we have to do m * already + // why? a few reasons + // a) this lovely comment in cairo's source - http://cgit.freedesktop.org/cairo/tree/src/cairo-matrix.c?id=0537479bd1d4c5a3bc0f6f41dec4deb98481f34a#n330 + // Direct2D uses column vectors and I don't know if this is even documented + // b) that's what Core Graphics does + // TODO see if Microsoft says to do this + dm = dm * cur; // for whatever reason operator * is defined but not operator *= + c->rt->SetTransform(&dm); +} + +void uiDrawClip(uiDrawContext *c, uiDrawPath *path) +{ + ID2D1PathGeometry *newPath; + ID2D1GeometrySink *newSink; + HRESULT hr; + + // if there's no current clip, borrow the path + if (c->currentClip == NULL) { + c->currentClip = pathGeometry(path); + // we have to take our own reference to that clip + c->currentClip->AddRef(); + return; + } + + // otherwise we have to intersect the current path with the new one + // we do that into a new path, and then replace c->currentClip with that new path + hr = d2dfactory->CreatePathGeometry(&newPath); + if (hr != S_OK) + logHRESULT(L"error creating new path", hr); + hr = newPath->Open(&newSink); + if (hr != S_OK) + logHRESULT(L"error opening new path", hr); + hr = c->currentClip->CombineWithGeometry( + pathGeometry(path), + D2D1_COMBINE_MODE_INTERSECT, + NULL, + // TODO is this correct or can this be set per target? + D2D1_DEFAULT_FLATTENING_TOLERANCE, + newSink); + if (hr != S_OK) + logHRESULT(L"error intersecting old path with new path", hr); + hr = newSink->Close(); + if (hr != S_OK) + logHRESULT(L"error closing new path", hr); + newSink->Release(); + + // okay we have the new clip; we just need to replace the old one with it + c->currentClip->Release(); + c->currentClip = newPath; + // we have a reference already; no need for another +} + +struct drawState { + ID2D1DrawingStateBlock *dsb; + ID2D1PathGeometry *clip; +}; + +void uiDrawSave(uiDrawContext *c) +{ + struct drawState state; + HRESULT hr; + + hr = d2dfactory->CreateDrawingStateBlock( + // TODO verify that these are correct + NULL, + NULL, + &(state.dsb)); + if (hr != S_OK) + logHRESULT(L"error creating drawing state block", hr); + c->rt->SaveDrawingState(state.dsb); + + // if we have a clip, we need to hold another reference to it + if (c->currentClip != NULL) + c->currentClip->AddRef(); + state.clip = c->currentClip; // even if NULL assign it + + c->states->push_back(state); +} + +void uiDrawRestore(uiDrawContext *c) +{ + struct drawState state; + + state = (*(c->states))[c->states->size() - 1]; + c->states->pop_back(); + + c->rt->RestoreDrawingState(state.dsb); + state.dsb->Release(); + + // if we have a current clip, we need to drop it + if (c->currentClip != NULL) + c->currentClip->Release(); + // no need to explicitly addref or release; just transfer the ref + c->currentClip = state.clip; +} diff --git a/dep/libui/windows/draw.hpp b/dep/libui/windows/draw.hpp new file mode 100644 index 0000000..c271e4d --- /dev/null +++ b/dep/libui/windows/draw.hpp @@ -0,0 +1,18 @@ +// 5 may 2016 + +// TODO resolve overlap between this and the other hpp files (some functions leaked into uipriv_windows.hpp) + +// draw.cpp +extern ID2D1Factory *d2dfactory; +struct uiDrawContext { + ID2D1RenderTarget *rt; + // TODO find out how this works + std::vector *states; + ID2D1PathGeometry *currentClip; +}; + +// drawpath.cpp +extern ID2D1PathGeometry *pathGeometry(uiDrawPath *p); + +// drawmatrix.cpp +extern void m2d(uiDrawMatrix *m, D2D1_MATRIX_3X2_F *d); diff --git a/dep/libui/windows/drawmatrix.cpp b/dep/libui/windows/drawmatrix.cpp new file mode 100644 index 0000000..4ddc5e9 --- /dev/null +++ b/dep/libui/windows/drawmatrix.cpp @@ -0,0 +1,117 @@ +// 7 september 2015 +#include "uipriv_windows.hpp" +#include "draw.hpp" + +void m2d(uiDrawMatrix *m, D2D1_MATRIX_3X2_F *d) +{ + d->_11 = m->M11; + d->_12 = m->M12; + d->_21 = m->M21; + d->_22 = m->M22; + d->_31 = m->M31; + d->_32 = m->M32; +} + +static void d2m(D2D1_MATRIX_3X2_F *d, uiDrawMatrix *m) +{ + m->M11 = d->_11; + m->M12 = d->_12; + m->M21 = d->_21; + m->M22 = d->_22; + m->M31 = d->_31; + m->M32 = d->_32; +} + +void uiDrawMatrixTranslate(uiDrawMatrix *m, double x, double y) +{ + D2D1_MATRIX_3X2_F dm; + + m2d(m, &dm); + dm = dm * D2D1::Matrix3x2F::Translation(x, y); + d2m(&dm, m); +} + +void uiDrawMatrixScale(uiDrawMatrix *m, double xCenter, double yCenter, double x, double y) +{ + D2D1_MATRIX_3X2_F dm; + D2D1_POINT_2F center; + + m2d(m, &dm); + center.x = xCenter; + center.y = yCenter; + dm = dm * D2D1::Matrix3x2F::Scale(x, y, center); + d2m(&dm, m); +} + +#define r2d(x) (x * (180.0 / uiPi)) + +void uiDrawMatrixRotate(uiDrawMatrix *m, double x, double y, double amount) +{ + D2D1_MATRIX_3X2_F dm; + D2D1_POINT_2F center; + + m2d(m, &dm); + center.x = x; + center.y = y; + dm = dm * D2D1::Matrix3x2F::Rotation(r2d(amount), center); + d2m(&dm, m); +} + +void uiDrawMatrixSkew(uiDrawMatrix *m, double x, double y, double xamount, double yamount) +{ + D2D1_MATRIX_3X2_F dm; + D2D1_POINT_2F center; + + m2d(m, &dm); + center.x = x; + center.y = y; + dm = dm * D2D1::Matrix3x2F::Skew(r2d(xamount), r2d(yamount), center); + d2m(&dm, m); +} + +void uiDrawMatrixMultiply(uiDrawMatrix *dest, uiDrawMatrix *src) +{ + D2D1_MATRIX_3X2_F c, d; + + m2d(dest, &c); + m2d(src, &d); + c = c * d; + d2m(&c, dest); +} + +int uiDrawMatrixInvertible(uiDrawMatrix *m) +{ + D2D1_MATRIX_3X2_F d; + + m2d(m, &d); + return D2D1IsMatrixInvertible(&d) != FALSE; +} + +int uiDrawMatrixInvert(uiDrawMatrix *m) +{ + D2D1_MATRIX_3X2_F d; + + m2d(m, &d); + if (D2D1InvertMatrix(&d) == FALSE) + return 0; + d2m(&d, m); + return 1; +} + +void uiDrawMatrixTransformPoint(uiDrawMatrix *m, double *x, double *y) +{ + D2D1::Matrix3x2F dm; + D2D1_POINT_2F pt; + + m2d(m, &dm); + pt.x = *x; + pt.y = *y; + pt = dm.TransformPoint(pt); + *x = pt.x; + *y = pt.y; +} + +void uiDrawMatrixTransformSize(uiDrawMatrix *m, double *x, double *y) +{ + uiprivFallbackTransformSize(m, x, y); +} diff --git a/dep/libui/windows/drawpath.cpp b/dep/libui/windows/drawpath.cpp new file mode 100644 index 0000000..34b1546 --- /dev/null +++ b/dep/libui/windows/drawpath.cpp @@ -0,0 +1,247 @@ +// 7 september 2015 +#include "uipriv_windows.hpp" +#include "draw.hpp" + +// TODO +// - write a test for transform followed by clip and clip followed by transform to make sure they work the same as on gtk+ and cocoa +// - write a test for nested transforms for gtk+ + +struct uiDrawPath { + ID2D1PathGeometry *path; + ID2D1GeometrySink *sink; + BOOL inFigure; +}; + +uiDrawPath *uiDrawNewPath(uiDrawFillMode fillmode) +{ + uiDrawPath *p; + HRESULT hr; + + p = uiprivNew(uiDrawPath); + hr = d2dfactory->CreatePathGeometry(&(p->path)); + if (hr != S_OK) + logHRESULT(L"error creating path", hr); + hr = p->path->Open(&(p->sink)); + if (hr != S_OK) + logHRESULT(L"error opening path", hr); + switch (fillmode) { + case uiDrawFillModeWinding: + p->sink->SetFillMode(D2D1_FILL_MODE_WINDING); + break; + case uiDrawFillModeAlternate: + p->sink->SetFillMode(D2D1_FILL_MODE_ALTERNATE); + break; + } + return p; +} + +void uiDrawFreePath(uiDrawPath *p) +{ + if (p->inFigure) + p->sink->EndFigure(D2D1_FIGURE_END_OPEN); + if (p->sink != NULL) + // TODO close sink first? + p->sink->Release(); + p->path->Release(); + uiprivFree(p); +} + +void uiDrawPathNewFigure(uiDrawPath *p, double x, double y) +{ + D2D1_POINT_2F pt; + + if (p->inFigure) + p->sink->EndFigure(D2D1_FIGURE_END_OPEN); + pt.x = x; + pt.y = y; + p->sink->BeginFigure(pt, D2D1_FIGURE_BEGIN_FILLED); + p->inFigure = TRUE; +} + +// Direct2D arcs require a little explanation. +// An arc in Direct2D is defined by the chord between the endpoints. +// There are four possible arcs with the same two endpoints that you can draw this way. +// See https://www.youtube.com/watch?v=ATS0ANW1UxQ for a demonstration. +// There is a property rotationAngle which deals with the rotation /of the entire ellipse that forms an ellpitical arc/ - it's effectively a transformation on the arc. +// That is to say, it's NOT THE SWEEP. +// The sweep is defined by the start and end points and whether the arc is "large". +// As a result, this design does not allow for full circles or ellipses with a single arc; they have to be simulated with two. +// TODO https://github.com/Microsoft/WinObjC/blob/develop/Frameworks/CoreGraphics/CGPath.mm#L313 + +struct arc { + double xCenter; + double yCenter; + double radius; + double startAngle; + double sweep; + int negative; +}; + +// this is used for the comparison below +// if it falls apart it can be changed later +#define aerMax 6 * DBL_EPSILON + +static void drawArc(uiDrawPath *p, struct arc *a, void (*startFunction)(uiDrawPath *, double, double)) +{ + double sinx, cosx; + double startX, startY; + double endX, endY; + D2D1_ARC_SEGMENT as; + BOOL fullCircle; + double absSweep; + + // as above, we can't do a full circle with one arc + // simulate it with two half-circles + // of course, we have a dragon: equality on floating-point values! + // I've chosen to do the AlmostEqualRelative() technique in https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ + fullCircle = FALSE; + // use the absolute value to tackle both ≥2π and ≤-2π at the same time + absSweep = fabs(a->sweep); + if (absSweep > (2 * uiPi)) // this part is easy + fullCircle = TRUE; + else { + double aerDiff; + + aerDiff = fabs(absSweep - (2 * uiPi)); + // if we got here then we know a->sweep is larger (or the same!) + fullCircle = aerDiff <= absSweep * aerMax; + } + // TODO make sure this works right for the negative direction + if (fullCircle) { + a->sweep = uiPi; + drawArc(p, a, startFunction); + a->startAngle += uiPi; + drawArc(p, a, NULL); + return; + } + + // first, figure out the arc's endpoints + // unfortunately D2D1SinCos() is only defined on Windows 8 and newer + // the MSDN page doesn't say this, but says it requires d2d1_1.h, which is listed as only supported on Windows 8 and newer elsewhere on MSDN + // so we must use sin() and cos() and hope it's right... + sinx = sin(a->startAngle); + cosx = cos(a->startAngle); + startX = a->xCenter + a->radius * cosx; + startY = a->yCenter + a->radius * sinx; + sinx = sin(a->startAngle + a->sweep); + cosx = cos(a->startAngle + a->sweep); + endX = a->xCenter + a->radius * cosx; + endY = a->yCenter + a->radius * sinx; + + // now do the initial step to get the current point to be the start point + // this is either creating a new figure, drawing a line, or (in the case of our full circle code above) doing nothing + if (startFunction != NULL) + (*startFunction)(p, startX, startY); + + // now we can draw the arc + as.point.x = endX; + as.point.y = endY; + as.size.width = a->radius; + as.size.height = a->radius; + as.rotationAngle = 0; // as above, not relevant for circles + if (a->negative) + as.sweepDirection = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE; + else + as.sweepDirection = D2D1_SWEEP_DIRECTION_CLOCKWISE; + // TODO explain the outer if + if (!a->negative) + if (a->sweep > uiPi) + as.arcSize = D2D1_ARC_SIZE_LARGE; + else + as.arcSize = D2D1_ARC_SIZE_SMALL; + else + // TODO especially this part + if (a->sweep > uiPi) + as.arcSize = D2D1_ARC_SIZE_SMALL; + else + as.arcSize = D2D1_ARC_SIZE_LARGE; + p->sink->AddArc(&as); +} + +void uiDrawPathNewFigureWithArc(uiDrawPath *p, double xCenter, double yCenter, double radius, double startAngle, double sweep, int negative) +{ + struct arc a; + + a.xCenter = xCenter; + a.yCenter = yCenter; + a.radius = radius; + a.startAngle = startAngle; + a.sweep = sweep; + a.negative = negative; + drawArc(p, &a, uiDrawPathNewFigure); +} + +void uiDrawPathLineTo(uiDrawPath *p, double x, double y) +{ + D2D1_POINT_2F pt; + + pt.x = x; + pt.y = y; + p->sink->AddLine(pt); +} + +void uiDrawPathArcTo(uiDrawPath *p, double xCenter, double yCenter, double radius, double startAngle, double sweep, int negative) +{ + struct arc a; + + a.xCenter = xCenter; + a.yCenter = yCenter; + a.radius = radius; + a.startAngle = startAngle; + a.sweep = sweep; + a.negative = negative; + drawArc(p, &a, uiDrawPathLineTo); +} + +void uiDrawPathBezierTo(uiDrawPath *p, double c1x, double c1y, double c2x, double c2y, double endX, double endY) +{ + D2D1_BEZIER_SEGMENT s; + + s.point1.x = c1x; + s.point1.y = c1y; + s.point2.x = c2x; + s.point2.y = c2y; + s.point3.x = endX; + s.point3.y = endY; + p->sink->AddBezier(&s); +} + +void uiDrawPathCloseFigure(uiDrawPath *p) +{ + p->sink->EndFigure(D2D1_FIGURE_END_CLOSED); + p->inFigure = FALSE; +} + +void uiDrawPathAddRectangle(uiDrawPath *p, double x, double y, double width, double height) +{ + // this is the same algorithm used by cairo and Core Graphics, according to their documentations + uiDrawPathNewFigure(p, x, y); + uiDrawPathLineTo(p, x + width, y); + uiDrawPathLineTo(p, x + width, y + height); + uiDrawPathLineTo(p, x, y + height); + uiDrawPathCloseFigure(p); +} + +void uiDrawPathEnd(uiDrawPath *p) +{ + HRESULT hr; + + if (p->inFigure) { + p->sink->EndFigure(D2D1_FIGURE_END_OPEN); + // needed for uiDrawFreePath() + p->inFigure = FALSE; + } + hr = p->sink->Close(); + if (hr != S_OK) + logHRESULT(L"error closing path", hr); + p->sink->Release(); + // also needed for uiDrawFreePath() + p->sink = NULL; +} + +ID2D1PathGeometry *pathGeometry(uiDrawPath *p) +{ + if (p->sink != NULL) + uiprivUserBug("You cannot draw with a uiDrawPath that was not ended. (path: %p)", p); + return p->path; +} diff --git a/dep/libui/windows/drawtext.cpp b/dep/libui/windows/drawtext.cpp new file mode 100644 index 0000000..ec2ae15 --- /dev/null +++ b/dep/libui/windows/drawtext.cpp @@ -0,0 +1,536 @@ +// 17 january 2017 +#include "uipriv_windows.hpp" +#include "draw.hpp" +#include "attrstr.hpp" + +// TODO verify our renderer is correct, especially with regards to snapping + +struct uiDrawTextLayout { + IDWriteTextFormat *format; + IDWriteTextLayout *layout; + std::vector *backgroundParams; + // for converting DirectWrite indices from/to byte offsets + size_t *u8tou16; + size_t nUTF8; + size_t *u16tou8; + size_t nUTF16; +}; + +// TODO copy notes about DirectWrite DIPs being equal to Direct2D DIPs here + +// typographic points are 1/72 inch; this parameter is 1/96 inch +// fortunately Microsoft does this too, in https://msdn.microsoft.com/en-us/library/windows/desktop/dd371554%28v=vs.85%29.aspx +#define pointSizeToDWriteSize(size) (size * (96.0 / 72.0)) + +// TODO move this and the layout creation stuff to attrstr.cpp like the other ports, or move the other ports into their drawtext.* files +// TODO should be const but then I can't operator[] on it; the real solution is to find a way to do designated array initializers in C++11 but I do not know enough C++ voodoo to make it work (it is possible but no one else has actually done it before) +static std::map dwriteAligns = { + { uiDrawTextAlignLeft, DWRITE_TEXT_ALIGNMENT_LEADING }, + { uiDrawTextAlignCenter, DWRITE_TEXT_ALIGNMENT_CENTER }, + { uiDrawTextAlignRight, DWRITE_TEXT_ALIGNMENT_TRAILING }, +}; + +uiDrawTextLayout *uiDrawNewTextLayout(uiDrawTextLayoutParams *p) +{ + uiDrawTextLayout *tl; + WCHAR *wDefaultFamily; + DWRITE_WORD_WRAPPING wrap; + FLOAT maxWidth; + HRESULT hr; + + tl = uiprivNew(uiDrawTextLayout); + + wDefaultFamily = toUTF16(p->DefaultFont->Family); + hr = dwfactory->CreateTextFormat( + wDefaultFamily, NULL, + uiprivWeightToDWriteWeight(p->DefaultFont->Weight), + uiprivItalicToDWriteStyle(p->DefaultFont->Italic), + uiprivStretchToDWriteStretch(p->DefaultFont->Stretch), + pointSizeToDWriteSize(p->DefaultFont->Size), + // see http://stackoverflow.com/questions/28397971/idwritefactorycreatetextformat-failing and https://msdn.microsoft.com/en-us/library/windows/desktop/dd368203.aspx + // TODO use the current locale? + L"", + &(tl->format)); + uiprivFree(wDefaultFamily); + if (hr != S_OK) + logHRESULT(L"error creating IDWriteTextFormat", hr); + hr = tl->format->SetTextAlignment(dwriteAligns[p->Align]); + if (hr != S_OK) + logHRESULT(L"error applying text layout alignment", hr); + + hr = dwfactory->CreateTextLayout( + (const WCHAR *) uiprivAttributedStringUTF16String(p->String), uiprivAttributedStringUTF16Len(p->String), + tl->format, + // FLOAT is float, not double, so this should work... TODO + FLT_MAX, FLT_MAX, + &(tl->layout)); + if (hr != S_OK) + logHRESULT(L"error creating IDWriteTextLayout", hr); + + // and set the width + // this is the only wrapping mode (apart from "no wrap") available prior to Windows 8.1 (TODO verify this fact) (TODO this should be the default anyway) + wrap = DWRITE_WORD_WRAPPING_WRAP; + maxWidth = (FLOAT) (p->Width); + if (p->Width < 0) { + // TODO is this wrapping juggling even necessary? + wrap = DWRITE_WORD_WRAPPING_NO_WRAP; + // setting the max width in this case technically isn't needed since the wrap mode will simply ignore the max width, but let's do it just to be safe + maxWidth = FLT_MAX; // see TODO above + } + hr = tl->layout->SetWordWrapping(wrap); + if (hr != S_OK) + logHRESULT(L"error setting IDWriteTextLayout word wrapping mode", hr); + hr = tl->layout->SetMaxWidth(maxWidth); + if (hr != S_OK) + logHRESULT(L"error setting IDWriteTextLayout max layout width", hr); + + uiprivAttributedStringApplyAttributesToDWriteTextLayout(p, tl->layout, &(tl->backgroundParams)); + + // and finally copy the UTF-8/UTF-16 index conversion tables + tl->u8tou16 = uiprivAttributedStringCopyUTF8ToUTF16Table(p->String, &(tl->nUTF8)); + tl->u16tou8 = uiprivAttributedStringCopyUTF16ToUTF8Table(p->String, &(tl->nUTF16)); + + return tl; +} + +void uiDrawFreeTextLayout(uiDrawTextLayout *tl) +{ + uiprivFree(tl->u16tou8); + uiprivFree(tl->u8tou16); + for (auto p : *(tl->backgroundParams)) + uiprivFree(p); + delete tl->backgroundParams; + tl->layout->Release(); + tl->format->Release(); + uiprivFree(tl); +} + +// TODO make this shared code somehow +static HRESULT mkSolidBrush(ID2D1RenderTarget *rt, double r, double g, double b, double a, ID2D1SolidColorBrush **brush) +{ + D2D1_BRUSH_PROPERTIES props; + D2D1_COLOR_F color; + + ZeroMemory(&props, sizeof (D2D1_BRUSH_PROPERTIES)); + props.opacity = 1.0; + // identity matrix + props.transform._11 = 1; + props.transform._22 = 1; + color.r = r; + color.g = g; + color.b = b; + color.a = a; + return rt->CreateSolidColorBrush( + &color, + &props, + brush); +} + +static ID2D1SolidColorBrush *mustMakeSolidBrush(ID2D1RenderTarget *rt, double r, double g, double b, double a) +{ + ID2D1SolidColorBrush *brush; + HRESULT hr; + + hr = mkSolidBrush(rt, r, g, b, a, &brush); + if (hr != S_OK) + logHRESULT(L"error creating solid brush", hr); + return brush; +} + +// some of the stuff we want to do isn't possible with what DirectWrite provides itself; we need to do it ourselves + +drawingEffectsAttr::drawingEffectsAttr(void) +{ + this->refcount = 1; + this->hasColor = false; + this->hasUnderline = false; + this->hasUnderlineColor = false; +} + +HRESULT STDMETHODCALLTYPE drawingEffectsAttr::QueryInterface(REFIID riid, void **ppvObject) +{ + if (ppvObject == NULL) + return E_POINTER; + if (riid == IID_IUnknown) { + this->AddRef(); + *ppvObject = this; + return S_OK; + } + *ppvObject = NULL; + return E_NOINTERFACE; +} + +ULONG STDMETHODCALLTYPE drawingEffectsAttr::AddRef(void) +{ + this->refcount++; + return this->refcount; +} + +ULONG STDMETHODCALLTYPE drawingEffectsAttr::Release(void) +{ + this->refcount--; + if (this->refcount == 0) { + delete this; + return 0; + } + return this->refcount; +} + +void drawingEffectsAttr::setColor(double r, double g, double b, double a) +{ + this->hasColor = true; + this->r = r; + this->g = g; + this->b = b; + this->a = a; +} + +void drawingEffectsAttr::setUnderline(uiUnderline u) +{ + this->hasUnderline = true; + this->u = u; +} + +void drawingEffectsAttr::setUnderlineColor(double r, double g, double b, double a) +{ + this->hasUnderlineColor = true; + this->ur = r; + this->ug = g; + this->ub = b; + this->ua = a; +} + +HRESULT drawingEffectsAttr::mkColorBrush(ID2D1RenderTarget *rt, ID2D1SolidColorBrush **b) +{ + if (!this->hasColor) { + *b = NULL; + return S_OK; + } + return mkSolidBrush(rt, this->r, this->g, this->b, this->a, b); +} + +HRESULT drawingEffectsAttr::underline(uiUnderline *u) +{ + if (u == NULL) + return E_POINTER; + if (!this->hasUnderline) + return E_UNEXPECTED; + *u = this->u; + return S_OK; +} + +HRESULT drawingEffectsAttr::mkUnderlineBrush(ID2D1RenderTarget *rt, ID2D1SolidColorBrush **b) +{ + if (!this->hasUnderlineColor) { + *b = NULL; + return S_OK; + } + return mkSolidBrush(rt, this->ur, this->ug, this->ub, this->ua, b); +} + +// this is based on http://www.charlespetzold.com/blog/2014/01/Character-Formatting-Extensions-with-DirectWrite.html +class textRenderer : public IDWriteTextRenderer { + ULONG refcount; + ID2D1RenderTarget *rt; + BOOL snap; + ID2D1SolidColorBrush *black; +public: + textRenderer(ID2D1RenderTarget *rt, BOOL snap, ID2D1SolidColorBrush *black) + { + this->refcount = 1; + this->rt = rt; + this->snap = snap; + this->black = black; + } + + // IUnknown + virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) + { + if (ppvObject == NULL) + return E_POINTER; + if (riid == IID_IUnknown || + riid == __uuidof (IDWritePixelSnapping) || + riid == __uuidof (IDWriteTextRenderer)) { + this->AddRef(); + *ppvObject = this; + return S_OK; + } + *ppvObject = NULL; + return E_NOINTERFACE; + } + + virtual ULONG STDMETHODCALLTYPE AddRef(void) + { + this->refcount++; + return this->refcount; + } + + virtual ULONG STDMETHODCALLTYPE Release(void) + { + this->refcount--; + if (this->refcount == 0) { + delete this; + return 0; + } + return this->refcount; + } + + // IDWritePixelSnapping + virtual HRESULT STDMETHODCALLTYPE GetCurrentTransform(void *clientDrawingContext, DWRITE_MATRIX *transform) + { + D2D1_MATRIX_3X2_F d2dtf; + + if (transform == NULL) + return E_POINTER; + this->rt->GetTransform(&d2dtf); + transform->m11 = d2dtf._11; + transform->m12 = d2dtf._12; + transform->m21 = d2dtf._21; + transform->m22 = d2dtf._22; + transform->dx = d2dtf._31; + transform->dy = d2dtf._32; + return S_OK; + } + + virtual HRESULT STDMETHODCALLTYPE GetPixelsPerDip(void *clientDrawingContext, FLOAT *pixelsPerDip) + { + FLOAT dpix, dpiy; + + if (pixelsPerDip == NULL) + return E_POINTER; + this->rt->GetDpi(&dpix, &dpiy); + *pixelsPerDip = dpix / 96; + return S_OK; + } + + virtual HRESULT STDMETHODCALLTYPE IsPixelSnappingDisabled(void *clientDrawingContext, BOOL *isDisabled) + { + if (isDisabled == NULL) + return E_POINTER; + *isDisabled = !this->snap; + return S_OK; + } + + // IDWriteTextRenderer + virtual HRESULT STDMETHODCALLTYPE DrawGlyphRun(void *clientDrawingContext, FLOAT baselineOriginX, FLOAT baselineOriginY, DWRITE_MEASURING_MODE measuringMode, const DWRITE_GLYPH_RUN *glyphRun, const DWRITE_GLYPH_RUN_DESCRIPTION *glyphRunDescription, IUnknown *clientDrawingEffect) + { + D2D1_POINT_2F baseline; + drawingEffectsAttr *dea = (drawingEffectsAttr *) clientDrawingEffect; + ID2D1SolidColorBrush *brush; + + baseline.x = baselineOriginX; + baseline.y = baselineOriginY; + brush = NULL; + if (dea != NULL) { + HRESULT hr; + + hr = dea->mkColorBrush(this->rt, &brush); + if (hr != S_OK) + return hr; + } + if (brush == NULL) { + brush = this->black; + brush->AddRef(); + } + this->rt->DrawGlyphRun( + baseline, + glyphRun, + brush, + measuringMode); + brush->Release(); + return S_OK; + } + + virtual HRESULT STDMETHODCALLTYPE DrawInlineObject(void *clientDrawingContext, FLOAT originX, FLOAT originY, IDWriteInlineObject *inlineObject, BOOL isSideways, BOOL isRightToLeft, IUnknown *clientDrawingEffect) + { + if (inlineObject == NULL) + return E_POINTER; + return inlineObject->Draw(clientDrawingContext, this, + originX, originY, + isSideways, isRightToLeft, + clientDrawingEffect); + } + + virtual HRESULT STDMETHODCALLTYPE DrawStrikethrough(void *clientDrawingContext, FLOAT baselineOriginX, FLOAT baselineOriginY, const DWRITE_STRIKETHROUGH *strikethrough, IUnknown *clientDrawingEffect) + { + // we don't support strikethrough + return E_UNEXPECTED; + } + + // TODO clean this function up + virtual HRESULT STDMETHODCALLTYPE DrawUnderline(void *clientDrawingContext, FLOAT baselineOriginX, FLOAT baselineOriginY, const DWRITE_UNDERLINE *underline, IUnknown *clientDrawingEffect) + { + drawingEffectsAttr *dea = (drawingEffectsAttr *) clientDrawingEffect; + uiUnderline utype; + ID2D1SolidColorBrush *brush; + D2D1_RECT_F rect; + D2D1::Matrix3x2F pixeltf; + FLOAT dpix, dpiy; + D2D1_POINT_2F pt; + HRESULT hr; + + if (underline == NULL) + return E_POINTER; + if (dea == NULL) // we can only get here through an underline + return E_UNEXPECTED; + hr = dea->underline(&utype); + if (hr != S_OK) // we *should* only get here through an underline that's actually set... + return hr; + hr = dea->mkUnderlineBrush(this->rt, &brush); + if (hr != S_OK) + return hr; + if (brush == NULL) { + // TODO document this rule if not already done + hr = dea->mkColorBrush(this->rt, &brush); + if (hr != S_OK) + return hr; + } + if (brush == NULL) { + brush = this->black; + brush->AddRef(); + } + rect.left = baselineOriginX; + rect.top = baselineOriginY + underline->offset; + rect.right = rect.left + underline->width; + rect.bottom = rect.top + underline->thickness; + switch (utype) { + case uiUnderlineSingle: + this->rt->FillRectangle(&rect, brush); + break; + case uiUnderlineDouble: + // TODO do any of the matrix methods return errors? + // TODO standardize double-underline shape across platforms? wavy underline shape? + this->rt->GetTransform(&pixeltf); + this->rt->GetDpi(&dpix, &dpiy); + pixeltf = pixeltf * D2D1::Matrix3x2F::Scale(dpix / 96, dpiy / 96); + pt.x = 0; + pt.y = rect.top; + pt = pixeltf.TransformPoint(pt); + rect.top = (FLOAT) ((int) (pt.y + 0.5)); + pixeltf.Invert(); + pt = pixeltf.TransformPoint(pt); + rect.top = pt.y; + // first line + rect.top -= underline->thickness; + // and it seems we need to recompute this + rect.bottom = rect.top + underline->thickness; + this->rt->FillRectangle(&rect, brush); + // second line + rect.top += 2 * underline->thickness; + rect.bottom = rect.top + underline->thickness; + this->rt->FillRectangle(&rect, brush); + break; + case uiUnderlineSuggestion: + { // TODO get rid of the extra block + // TODO properly clean resources on failure + // TODO use fully qualified C overloads for all methods + // TODO ensure all methods properly have errors handled + ID2D1PathGeometry *path; + ID2D1GeometrySink *sink; + double amplitude, period, xOffset, yOffset; + double t; + bool first = true; + HRESULT hr; + + hr = d2dfactory->CreatePathGeometry(&path); + if (hr != S_OK) + return hr; + hr = path->Open(&sink); + if (hr != S_OK) + return hr; + amplitude = underline->thickness; + period = 5 * underline->thickness; + xOffset = baselineOriginX; + yOffset = baselineOriginY + underline->offset; + for (t = 0; t < underline->width; t++) { + double x, angle, y; + D2D1_POINT_2F pt; + + x = t + xOffset; + angle = 2 * uiPi * fmod(x, period) / period; + y = amplitude * sin(angle) + yOffset; + pt.x = x; + pt.y = y; + if (first) { + sink->BeginFigure(pt, D2D1_FIGURE_BEGIN_HOLLOW); + first = false; + } else + sink->AddLine(pt); + } + sink->EndFigure(D2D1_FIGURE_END_OPEN); + hr = sink->Close(); + if (hr != S_OK) + return hr; + sink->Release(); + this->rt->DrawGeometry(path, brush, underline->thickness); + path->Release(); + } + break; + } + brush->Release(); + return S_OK; + } +}; + +// TODO this ignores clipping? +void uiDrawText(uiDrawContext *c, uiDrawTextLayout *tl, double x, double y) +{ + D2D1_POINT_2F pt; + ID2D1SolidColorBrush *black; + textRenderer *renderer; + HRESULT hr; + + for (auto p : *(tl->backgroundParams)) { + // TODO + } + + // TODO document that fully opaque black is the default text color; figure out whether this is upheld in various scenarios on other platforms + // TODO figure out if this needs to be cleaned out + black = mustMakeSolidBrush(c->rt, 0.0, 0.0, 0.0, 1.0); + +#define renderD2D 0 +#define renderOur 1 +#if renderD2D + pt.x = x; + pt.y = y; + // TODO D2D1_DRAW_TEXT_OPTIONS_NO_SNAP? + // TODO D2D1_DRAW_TEXT_OPTIONS_CLIP? + // TODO LONGTERM when setting 8.1 as minimum (TODO verify), D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT? + // TODO what is our pixel snapping setting related to the OPTIONS enum values? + c->rt->DrawTextLayout(pt, tl->layout, black, D2D1_DRAW_TEXT_OPTIONS_NONE); +#endif +#if renderD2D && renderOur + // draw ours semitransparent so we can check + // TODO get the actual color Charles Petzold uses and use that + black->Release(); + black = mustMakeSolidBrush(c->rt, 1.0, 0.0, 0.0, 0.75); +#endif +#if renderOur + renderer = new textRenderer(c->rt, + TRUE, // TODO FALSE for no-snap? + black); + hr = tl->layout->Draw(NULL, + renderer, + x, y); + if (hr != S_OK) + logHRESULT(L"error drawing IDWriteTextLayout", hr); + renderer->Release(); +#endif + + black->Release(); +} + +// TODO for a single line the height includes the leading; should it? TextEdit on OS X always includes the leading and/or paragraph spacing, otherwise Klee won't work... +// TODO width does not include trailing whitespace +void uiDrawTextLayoutExtents(uiDrawTextLayout *tl, double *width, double *height) +{ + DWRITE_TEXT_METRICS metrics; + HRESULT hr; + + hr = tl->layout->GetMetrics(&metrics); + if (hr != S_OK) + logHRESULT(L"error getting IDWriteTextLayout layout metrics", hr); + *width = metrics.width; + // TODO make sure the behavior of this on empty strings is the same on all platforms (ideally should be 0-width, line height-height; TODO note this in the docs too) + *height = metrics.height; +} diff --git a/dep/libui/windows/dwrite.cpp b/dep/libui/windows/dwrite.cpp new file mode 100644 index 0000000..4d6b674 --- /dev/null +++ b/dep/libui/windows/dwrite.cpp @@ -0,0 +1,90 @@ +// 14 april 2016 +#include "uipriv_windows.hpp" +#include "attrstr.hpp" + +IDWriteFactory *dwfactory = NULL; + +// TOOD rename to something else, maybe +HRESULT uiprivInitDrawText(void) +{ + // TOOD use DWRITE_FACTORY_TYPE_ISOLATED instead? + return DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, + __uuidof (IDWriteFactory), + (IUnknown **) (&dwfactory)); +} + +void uiprivUninitDrawText(void) +{ + dwfactory->Release(); +} + +fontCollection *uiprivLoadFontCollection(void) +{ + fontCollection *fc; + HRESULT hr; + + fc = uiprivNew(fontCollection); + // always get the latest available font information + hr = dwfactory->GetSystemFontCollection(&(fc->fonts), TRUE); + if (hr != S_OK) + logHRESULT(L"error getting system font collection", hr); + fc->userLocaleSuccess = GetUserDefaultLocaleName(fc->userLocale, LOCALE_NAME_MAX_LENGTH); + return fc; +} + +void uiprivFontCollectionFree(fontCollection *fc) +{ + fc->fonts->Release(); + uiprivFree(fc); +} + +WCHAR *uiprivFontCollectionFamilyName(fontCollection *fc, IDWriteFontFamily *family) +{ + IDWriteLocalizedStrings *names; + WCHAR *str; + HRESULT hr; + + hr = family->GetFamilyNames(&names); + if (hr != S_OK) + logHRESULT(L"error getting names of font out", hr); + str = uiprivFontCollectionCorrectString(fc, names); + names->Release(); + return str; +} + +WCHAR *uiprivFontCollectionCorrectString(fontCollection *fc, IDWriteLocalizedStrings *names) +{ + UINT32 index; + BOOL exists; + UINT32 length; + WCHAR *wname; + HRESULT hr; + + // this is complex, but we ignore failure conditions to allow fallbacks + // 1) If the user locale name was successfully retrieved, try it + // 2) If the user locale name was not successfully retrieved, or that locale's string does not exist, or an error occurred, try L"en-us", the US English locale + // 3) And if that fails, assume the first one + // This algorithm is straight from MSDN: https://msdn.microsoft.com/en-us/library/windows/desktop/dd368214%28v=vs.85%29.aspx + // For step 2 to work, start by setting hr to S_OK and exists to FALSE. + // TODO does it skip step 2 entirely if step 1 fails? rewrite it to be a more pure conversion of the MSDN code? + hr = S_OK; + exists = FALSE; + if (fc->userLocaleSuccess != 0) + hr = names->FindLocaleName(fc->userLocale, &index, &exists); + if (hr != S_OK || (hr == S_OK && !exists)) + hr = names->FindLocaleName(L"en-us", &index, &exists); + // TODO check hr again here? or did I decide that would be redundant because COM requires output arguments to be filled regardless of return value? + if (!exists) + index = 0; + + hr = names->GetStringLength(index, &length); + if (hr != S_OK) + logHRESULT(L"error getting length of font name", hr); + // GetStringLength() does not include the null terminator, but GetString() does + wname = (WCHAR *) uiprivAlloc((length + 1) * sizeof (WCHAR), "WCHAR[]"); + hr = names->GetString(index, wname, length + 1); + if (hr != S_OK) + logHRESULT(L"error getting font name", hr); + + return wname; +} diff --git a/dep/libui/windows/editablecombo.cpp b/dep/libui/windows/editablecombo.cpp new file mode 100644 index 0000000..f1831bb --- /dev/null +++ b/dep/libui/windows/editablecombo.cpp @@ -0,0 +1,117 @@ +// 20 may 2015 +#include "uipriv_windows.hpp" + +// TODO no scrollbars? also not sure if true for combobox as well + +// we as Common Controls 6 users don't need to worry about the height of comboboxes; see http://blogs.msdn.com/b/oldnewthing/archive/2006/03/10/548537.aspx + +struct uiEditableCombobox { + uiWindowsControl c; + HWND hwnd; + void (*onChanged)(uiEditableCombobox *, void *); + void *onChangedData; +}; + +static BOOL onWM_COMMAND(uiControl *cc, HWND hwnd, WORD code, LRESULT *lResult) +{ + uiEditableCombobox *c = uiEditableCombobox(cc); + + if (code == CBN_SELCHANGE) { + // like on OS X, this is sent before the edit has been updated :( + if (PostMessage(parentOf(hwnd), + WM_COMMAND, + MAKEWPARAM(GetWindowLongPtrW(hwnd, GWLP_ID), CBN_EDITCHANGE), + (LPARAM) hwnd) == 0) + logLastError(L"error posting CBN_EDITCHANGE after CBN_SELCHANGE"); + *lResult = 0; + return TRUE; + } + if (code != CBN_EDITCHANGE) + return FALSE; + (*(c->onChanged))(c, c->onChangedData); + *lResult = 0; + return TRUE; +} + +void uiEditableComboboxDestroy(uiControl *cc) +{ + uiEditableCombobox *c = uiEditableCombobox(cc); + + uiWindowsUnregisterWM_COMMANDHandler(c->hwnd); + uiWindowsEnsureDestroyWindow(c->hwnd); + uiFreeControl(uiControl(c)); +} + +uiWindowsControlAllDefaultsExceptDestroy(uiEditableCombobox) + +// from http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing +#define comboboxWidth 107 /* this is actually the shorter progress bar width, but Microsoft only indicates as wide as necessary; LONGTERM */ +#define comboboxHeight 14 /* LONGTERM: is this too high? */ + +static void uiEditableComboboxMinimumSize(uiWindowsControl *cc, int *width, int *height) +{ + uiEditableCombobox *c = uiEditableCombobox(cc); + uiWindowsSizing sizing; + int x, y; + + x = comboboxWidth; + y = comboboxHeight; + uiWindowsGetSizing(c->hwnd, &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, &x, &y); + *width = x; + *height = y; +} + +static void defaultOnChanged(uiEditableCombobox *c, void *data) +{ + // do nothing +} + +void uiEditableComboboxAppend(uiEditableCombobox *c, const char *text) +{ + WCHAR *wtext; + LRESULT res; + + wtext = toUTF16(text); + res = SendMessageW(c->hwnd, CB_ADDSTRING, 0, (LPARAM) wtext); + if (res == (LRESULT) CB_ERR) + logLastError(L"error appending item to uiEditableCombobox"); + else if (res == (LRESULT) CB_ERRSPACE) + logLastError(L"memory exhausted appending item to uiEditableCombobox"); + uiprivFree(wtext); +} + +char *uiEditableComboboxText(uiEditableCombobox *c) +{ + return uiWindowsWindowText(c->hwnd); +} + +void uiEditableComboboxSetText(uiEditableCombobox *c, const char *text) +{ + // does not trigger any notifications + uiWindowsSetWindowText(c->hwnd, text); +} + +void uiEditableComboboxOnChanged(uiEditableCombobox *c, void (*f)(uiEditableCombobox *c, void *data), void *data) +{ + c->onChanged = f; + c->onChangedData = data; +} + +uiEditableCombobox *uiNewEditableCombobox(void) +{ + uiEditableCombobox *c; + + uiWindowsNewControl(uiEditableCombobox, c); + + c->hwnd = uiWindowsEnsureCreateControlHWND(WS_EX_CLIENTEDGE, + L"combobox", L"", + CBS_DROPDOWN | WS_TABSTOP, + hInstance, NULL, + TRUE); + + uiWindowsRegisterWM_COMMANDHandler(c->hwnd, onWM_COMMAND, uiControl(c)); + uiEditableComboboxOnChanged(c, defaultOnChanged, NULL); + + return c; +} diff --git a/dep/libui/windows/entry.cpp b/dep/libui/windows/entry.cpp new file mode 100644 index 0000000..a7a077f --- /dev/null +++ b/dep/libui/windows/entry.cpp @@ -0,0 +1,134 @@ +// 8 april 2015 +#include "uipriv_windows.hpp" + +struct uiEntry { + uiWindowsControl c; + HWND hwnd; + void (*onChanged)(uiEntry *, void *); + void *onChangedData; + BOOL inhibitChanged; +}; + +static BOOL onWM_COMMAND(uiControl *c, HWND hwnd, WORD code, LRESULT *lResult) +{ + uiEntry *e = uiEntry(c); + + if (code != EN_CHANGE) + return FALSE; + if (e->inhibitChanged) + return FALSE; + (*(e->onChanged))(e, e->onChangedData); + *lResult = 0; + return TRUE; +} + +static void uiEntryDestroy(uiControl *c) +{ + uiEntry *e = uiEntry(c); + + uiWindowsUnregisterWM_COMMANDHandler(e->hwnd); + uiWindowsEnsureDestroyWindow(e->hwnd); + uiFreeControl(uiControl(e)); +} + +uiWindowsControlAllDefaultsExceptDestroy(uiEntry) + +// from http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing +#define entryWidth 107 /* this is actually the shorter progress bar width, but Microsoft only indicates as wide as necessary */ +#define entryHeight 14 + +static void uiEntryMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + uiEntry *e = uiEntry(c); + uiWindowsSizing sizing; + int x, y; + + x = entryWidth; + y = entryHeight; + uiWindowsGetSizing(e->hwnd, &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, &x, &y); + *width = x; + *height = y; +} + +static void defaultOnChanged(uiEntry *e, void *data) +{ + // do nothing +} + +char *uiEntryText(uiEntry *e) +{ + return uiWindowsWindowText(e->hwnd); +} + +void uiEntrySetText(uiEntry *e, const char *text) +{ + // doing this raises an EN_CHANGED + e->inhibitChanged = TRUE; + uiWindowsSetWindowText(e->hwnd, text); + e->inhibitChanged = FALSE; + // don't queue the control for resize; entry sizes are independent of their contents +} + +void uiEntryOnChanged(uiEntry *e, void (*f)(uiEntry *, void *), void *data) +{ + e->onChanged = f; + e->onChangedData = data; +} + +int uiEntryReadOnly(uiEntry *e) +{ + return (getStyle(e->hwnd) & ES_READONLY) != 0; +} + +void uiEntrySetReadOnly(uiEntry *e, int readonly) +{ + WPARAM ro; + + ro = (WPARAM) FALSE; + if (readonly) + ro = (WPARAM) TRUE; + if (SendMessage(e->hwnd, EM_SETREADONLY, ro, 0) == 0) + logLastError(L"error making uiEntry read-only"); +} + +static uiEntry *finishNewEntry(DWORD style) +{ + uiEntry *e; + + uiWindowsNewControl(uiEntry, e); + + e->hwnd = uiWindowsEnsureCreateControlHWND(WS_EX_CLIENTEDGE, + L"edit", L"", + style | ES_AUTOHSCROLL | ES_LEFT | ES_NOHIDESEL | WS_TABSTOP, + hInstance, NULL, + TRUE); + + uiWindowsRegisterWM_COMMANDHandler(e->hwnd, onWM_COMMAND, uiControl(e)); + uiEntryOnChanged(e, defaultOnChanged, NULL); + + return e; +} + +uiEntry *uiNewEntry(void) +{ + return finishNewEntry(0); +} + +uiEntry *uiNewPasswordEntry(void) +{ + return finishNewEntry(ES_PASSWORD); +} + +uiEntry *uiNewSearchEntry(void) +{ + uiEntry *e; + HRESULT hr; + + e = finishNewEntry(0); + // TODO this is from ThemeExplorer; is it documented anywhere? + // TODO SearchBoxEditComposited has no border + hr = SetWindowTheme(e->hwnd, L"SearchBoxEdit", NULL); + // TODO will hr be S_OK if themes are disabled? + return e; +} diff --git a/dep/libui/windows/events.cpp b/dep/libui/windows/events.cpp new file mode 100644 index 0000000..c13d6d0 --- /dev/null +++ b/dep/libui/windows/events.cpp @@ -0,0 +1,151 @@ +// 20 may 2015 +#include "uipriv_windows.hpp" + +struct handler { + BOOL (*commandHandler)(uiControl *, HWND, WORD, LRESULT *); + BOOL (*notifyHandler)(uiControl *, HWND, NMHDR *, LRESULT *); + BOOL (*hscrollHandler)(uiControl *, HWND, WORD, LRESULT *); + uiControl *c; + + // just to ensure handlers[new HWND] initializes properly + // TODO gcc can't handle a struct keyword here? or is that a MSVC extension? + handler() + { + this->commandHandler = NULL; + this->notifyHandler = NULL; + this->hscrollHandler = NULL; + this->c = NULL; + } +}; + +static std::map handlers; + +void uiWindowsRegisterWM_COMMANDHandler(HWND hwnd, BOOL (*handler)(uiControl *, HWND, WORD, LRESULT *), uiControl *c) +{ + if (handlers[hwnd].commandHandler != NULL) + uiprivImplBug("already registered a WM_COMMAND handler to window handle %p", hwnd); + handlers[hwnd].commandHandler = handler; + handlers[hwnd].c = c; +} + +void uiWindowsRegisterWM_NOTIFYHandler(HWND hwnd, BOOL (*handler)(uiControl *, HWND, NMHDR *, LRESULT *), uiControl *c) +{ + if (handlers[hwnd].notifyHandler != NULL) + uiprivImplBug("already registered a WM_NOTIFY handler to window handle %p", hwnd); + handlers[hwnd].notifyHandler = handler; + handlers[hwnd].c = c; +} + +void uiWindowsRegisterWM_HSCROLLHandler(HWND hwnd, BOOL (*handler)(uiControl *, HWND, WORD, LRESULT *), uiControl *c) +{ + if (handlers[hwnd].hscrollHandler != NULL) + uiprivImplBug("already registered a WM_HSCROLL handler to window handle %p", hwnd); + handlers[hwnd].hscrollHandler = handler; + handlers[hwnd].c = c; +} + +void uiWindowsUnregisterWM_COMMANDHandler(HWND hwnd) +{ + if (handlers[hwnd].commandHandler == NULL) + uiprivImplBug("window handle %p not registered to receive WM_COMMAND events", hwnd); + handlers[hwnd].commandHandler = NULL; +} + +void uiWindowsUnregisterWM_NOTIFYHandler(HWND hwnd) +{ + if (handlers[hwnd].notifyHandler == NULL) + uiprivImplBug("window handle %p not registered to receive WM_NOTIFY events", hwnd); + handlers[hwnd].notifyHandler = NULL; +} + +void uiWindowsUnregisterWM_HSCROLLHandler(HWND hwnd) +{ + if (handlers[hwnd].hscrollHandler == NULL) + uiprivImplBug("window handle %p not registered to receive WM_HSCROLL events", hwnd); + handlers[hwnd].hscrollHandler = NULL; +} + +template +static BOOL shouldRun(HWND hwnd, T method) +{ + // not from a window + if (hwnd == NULL) + return FALSE; + // don't bounce back if to the utility window, in which case act as if the message was ignored + if (IsChild(utilWindow, hwnd) != 0) + return FALSE; + // registered? + return method != NULL; +} + +BOOL runWM_COMMAND(WPARAM wParam, LPARAM lParam, LRESULT *lResult) +{ + HWND hwnd; + WORD arg3; + BOOL (*handler)(uiControl *, HWND, WORD, LRESULT *); + uiControl *c; + + hwnd = (HWND) lParam; + arg3 = HIWORD(wParam); + handler = handlers[hwnd].commandHandler; + c = handlers[hwnd].c; + if (shouldRun(hwnd, handler)) + return (*handler)(c, hwnd, arg3, lResult); + return FALSE; +} + +BOOL runWM_NOTIFY(WPARAM wParam, LPARAM lParam, LRESULT *lResult) +{ + HWND hwnd; + NMHDR *arg3; + BOOL (*handler)(uiControl *, HWND, NMHDR *, LRESULT *); + uiControl *c; + + arg3 = (NMHDR *) lParam; + hwnd = arg3->hwndFrom; + handler = handlers[hwnd].notifyHandler; + c = handlers[hwnd].c; + if (shouldRun(hwnd, handler)) + return (*handler)(c, hwnd, arg3, lResult); + return FALSE; +} + +BOOL runWM_HSCROLL(WPARAM wParam, LPARAM lParam, LRESULT *lResult) +{ + HWND hwnd; + WORD arg3; + BOOL (*handler)(uiControl *, HWND, WORD, LRESULT *); + uiControl *c; + + hwnd = (HWND) lParam; + arg3 = LOWORD(wParam); + handler = handlers[hwnd].hscrollHandler; + c = handlers[hwnd].c; + if (shouldRun(hwnd, handler)) + return (*handler)(c, hwnd, arg3, lResult); + return FALSE; +} + +static std::map wininichanges; + +void uiWindowsRegisterReceiveWM_WININICHANGE(HWND hwnd) +{ + if (wininichanges[hwnd]) + uiprivImplBug("window handle %p already subscribed to receive WM_WINICHANGEs", hwnd); + wininichanges[hwnd] = true; +} + +void uiWindowsUnregisterReceiveWM_WININICHANGE(HWND hwnd) +{ + if (!wininichanges[hwnd]) + uiprivImplBug("window handle %p not registered to receive WM_WININICHANGEs", hwnd); + wininichanges[hwnd] = false; +} + +void issueWM_WININICHANGE(WPARAM wParam, LPARAM lParam) +{ + struct wininichange *ch; + + for (const auto &iter : wininichanges) + SendMessageW(iter.first, WM_WININICHANGE, wParam, lParam); +} diff --git a/dep/libui/windows/fontbutton.cpp b/dep/libui/windows/fontbutton.cpp new file mode 100644 index 0000000..d6e5e0d --- /dev/null +++ b/dep/libui/windows/fontbutton.cpp @@ -0,0 +1,128 @@ +// 14 april 2016 +#include "uipriv_windows.hpp" +#include "attrstr.hpp" + +struct uiFontButton { + uiWindowsControl c; + HWND hwnd; + struct fontDialogParams params; + BOOL already; + void (*onChanged)(uiFontButton *, void *); + void *onChangedData; +}; + +static void uiFontButtonDestroy(uiControl *c) +{ + uiFontButton *b = uiFontButton(c); + + uiWindowsUnregisterWM_COMMANDHandler(b->hwnd); + uiprivDestroyFontDialogParams(&(b->params)); + uiWindowsEnsureDestroyWindow(b->hwnd); + uiFreeControl(uiControl(b)); +} + +static void updateFontButtonLabel(uiFontButton *b) +{ + WCHAR *text; + + text = uiprivFontDialogParamsToString(&(b->params)); + setWindowText(b->hwnd, text); + uiprivFree(text); + + // changing the text might necessitate a change in the button's size + uiWindowsControlMinimumSizeChanged(uiWindowsControl(b)); +} + +static BOOL onWM_COMMAND(uiControl *c, HWND hwnd, WORD code, LRESULT *lResult) +{ + uiFontButton *b = uiFontButton(c); + HWND parent; + + if (code != BN_CLICKED) + return FALSE; + + parent = parentToplevel(b->hwnd); + if (uiprivShowFontDialog(parent, &(b->params))) { + updateFontButtonLabel(b); + (*(b->onChanged))(b, b->onChangedData); + } + + *lResult = 0; + return TRUE; +} + +uiWindowsControlAllDefaultsExceptDestroy(uiFontButton) + +// from http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing +#define buttonHeight 14 + +static void uiFontButtonMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + uiFontButton *b = uiFontButton(c); + SIZE size; + uiWindowsSizing sizing; + int y; + + // try the comctl32 version 6 way + size.cx = 0; // explicitly ask for ideal size + size.cy = 0; + if (SendMessageW(b->hwnd, BCM_GETIDEALSIZE, 0, (LPARAM) (&size)) != FALSE) { + *width = size.cx; + *height = size.cy; + return; + } + + // that didn't work; fall back to using Microsoft's metrics + // Microsoft says to use a fixed width for all buttons; this isn't good enough + // use the text width instead, with some edge padding + *width = uiWindowsWindowTextWidth(b->hwnd) + (2 * GetSystemMetrics(SM_CXEDGE)); + y = buttonHeight; + uiWindowsGetSizing(b->hwnd, &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, NULL, &y); + *height = y; +} + +static void defaultOnChanged(uiFontButton *b, void *data) +{ + // do nothing +} + +void uiFontButtonFont(uiFontButton *b, uiFontDescriptor *desc) +{ + uiprivFontDescriptorFromIDWriteFont(b->params.font, desc); + desc->Family = toUTF8(b->params.familyName); + desc->Size = b->params.size; +} + +void uiFontButtonOnChanged(uiFontButton *b, void (*f)(uiFontButton *, void *), void *data) +{ + b->onChanged = f; + b->onChangedData = data; +} + +uiFontButton *uiNewFontButton(void) +{ + uiFontButton *b; + + uiWindowsNewControl(uiFontButton, b); + + b->hwnd = uiWindowsEnsureCreateControlHWND(0, + L"button", L"you should not be seeing this", + BS_PUSHBUTTON | WS_TABSTOP, + hInstance, NULL, + TRUE); + + uiprivLoadInitialFontDialogParams(&(b->params)); + + uiWindowsRegisterWM_COMMANDHandler(b->hwnd, onWM_COMMAND, uiControl(b)); + uiFontButtonOnChanged(b, defaultOnChanged, NULL); + + updateFontButtonLabel(b); + + return b; +} + +void uiFreeFontButtonFont(uiFontDescriptor *desc) +{ + uiprivFree((char *) (desc->Family)); +} diff --git a/dep/libui/windows/fontdialog.cpp b/dep/libui/windows/fontdialog.cpp new file mode 100644 index 0000000..4c69875 --- /dev/null +++ b/dep/libui/windows/fontdialog.cpp @@ -0,0 +1,787 @@ +// 14 april 2016 +#include "uipriv_windows.hpp" +#include "attrstr.hpp" + +// TODOs +// - quote the Choose Font sample here for reference +// - the Choose Font sample defaults to Regular/Italic/Bold/Bold Italic in some case (no styles?); do we? find out what the case is +// - do we set initial family and style topmost as well? +// - this should probably just handle IDWriteFonts +// - localization? +// - the Sample window overlaps the groupbox in a weird way (compare to the real ChooseFont() dialog) + +struct fontDialog { + HWND hwnd; + HWND familyCombobox; + HWND styleCombobox; + HWND sizeCombobox; + + struct fontDialogParams *params; + + struct fontCollection *fc; + + RECT sampleRect; + HWND sampleBox; + + // we store the current selections in case an invalid string is typed in (partial or nonexistent or invalid number) + // on OK, these are what are read + LRESULT curFamily; + LRESULT curStyle; + double curSize; + + // these are finding the style that's closest to the previous one (these fields) when changing a font + DWRITE_FONT_WEIGHT weight; + DWRITE_FONT_STYLE style; + DWRITE_FONT_STRETCH stretch; +}; + +static LRESULT cbAddString(HWND cb, const WCHAR *str) +{ + LRESULT lr; + + lr = SendMessageW(cb, CB_ADDSTRING, 0, (LPARAM) str); + if (lr == (LRESULT) CB_ERR || lr == (LRESULT) CB_ERRSPACE) + logLastError(L"error adding item to combobox"); + return lr; +} + +static LRESULT cbInsertString(HWND cb, const WCHAR *str, WPARAM pos) +{ + LRESULT lr; + + lr = SendMessageW(cb, CB_INSERTSTRING, pos, (LPARAM) str); + if (lr != (LRESULT) pos) + logLastError(L"error inserting item to combobox"); + return lr; +} + +static LRESULT cbGetItemData(HWND cb, WPARAM item) +{ + LRESULT data; + + data = SendMessageW(cb, CB_GETITEMDATA, item, 0); + if (data == (LRESULT) CB_ERR) + logLastError(L"error getting combobox item data for font dialog"); + return data; +} + +static void cbSetItemData(HWND cb, WPARAM item, LPARAM data) +{ + if (SendMessageW(cb, CB_SETITEMDATA, item, data) == (LRESULT) CB_ERR) + logLastError(L"error setting combobox item data"); +} + +static BOOL cbGetCurSel(HWND cb, LRESULT *sel) +{ + LRESULT n; + + n = SendMessageW(cb, CB_GETCURSEL, 0, 0); + if (n == (LRESULT) CB_ERR) + return FALSE; + if (sel != NULL) + *sel = n; + return TRUE; +} + +static void cbSetCurSel(HWND cb, WPARAM item) +{ + if (SendMessageW(cb, CB_SETCURSEL, item, 0) != (LRESULT) item) + logLastError(L"error selecting combobox item"); +} + +static LRESULT cbGetCount(HWND cb) +{ + LRESULT n; + + n = SendMessageW(cb, CB_GETCOUNT, 0, 0); + if (n == (LRESULT) CB_ERR) + logLastError(L"error getting combobox item count"); + return n; +} + +static void cbWipeAndReleaseData(HWND cb) +{ + IUnknown *obj; + LRESULT i, n; + + n = cbGetCount(cb); + for (i = 0; i < n; i++) { + obj = (IUnknown *) cbGetItemData(cb, (WPARAM) i); + obj->Release(); + } + SendMessageW(cb, CB_RESETCONTENT, 0, 0); +} + +static WCHAR *cbGetItemText(HWND cb, WPARAM item) +{ + LRESULT len; + WCHAR *text; + + // note: neither message includes the terminating L'\0' + len = SendMessageW(cb, CB_GETLBTEXTLEN, item, 0); + if (len == (LRESULT) CB_ERR) + logLastError(L"error getting item text length from combobox"); + text = (WCHAR *) uiprivAlloc((len + 1) * sizeof (WCHAR), "WCHAR[]"); + if (SendMessageW(cb, CB_GETLBTEXT, item, (LPARAM) text) != len) + logLastError(L"error getting item text from combobox"); + return text; +} + +static BOOL cbTypeToSelect(HWND cb, LRESULT *posOut, BOOL restoreAfter) +{ + WCHAR *text; + LRESULT pos; + DWORD selStart, selEnd; + + // start by saving the current selection as setting the item will change the selection + SendMessageW(cb, CB_GETEDITSEL, (WPARAM) (&selStart), (LPARAM) (&selEnd)); + text = windowText(cb); + pos = SendMessageW(cb, CB_FINDSTRINGEXACT, (WPARAM) (-1), (LPARAM) text); + if (pos == (LRESULT) CB_ERR) { + uiprivFree(text); + return FALSE; + } + cbSetCurSel(cb, (WPARAM) pos); + if (posOut != NULL) + *posOut = pos; + if (restoreAfter) + if (SendMessageW(cb, WM_SETTEXT, 0, (LPARAM) text) != (LRESULT) TRUE) + logLastError(L"error restoring old combobox text"); + uiprivFree(text); + // and restore the selection like above + // TODO isn't there a 32-bit version of this + if (SendMessageW(cb, CB_SETEDITSEL, 0, MAKELPARAM(selStart, selEnd)) != (LRESULT) TRUE) + logLastError(L"error restoring combobox edit selection"); + return TRUE; +} + +static void wipeStylesBox(struct fontDialog *f) +{ + cbWipeAndReleaseData(f->styleCombobox); +} + +static WCHAR *fontStyleName(struct fontCollection *fc, IDWriteFont *font) +{ + IDWriteLocalizedStrings *str; + WCHAR *wstr; + HRESULT hr; + + hr = font->GetFaceNames(&str); + if (hr != S_OK) + logHRESULT(L"error getting font style name for font dialog", hr); + wstr = uiprivFontCollectionCorrectString(fc, str); + str->Release(); + return wstr; +} + +static void queueRedrawSampleText(struct fontDialog *f) +{ + // TODO TRUE? + invalidateRect(f->sampleBox, NULL, TRUE); +} + +static void styleChanged(struct fontDialog *f) +{ + LRESULT pos; + BOOL selected; + IDWriteFont *font; + + selected = cbGetCurSel(f->styleCombobox, &pos); + if (!selected) // on deselect, do nothing + return; + f->curStyle = pos; + + font = (IDWriteFont *) cbGetItemData(f->styleCombobox, (WPARAM) (f->curStyle)); + // these are for the nearest match when changing the family; see below + f->weight = font->GetWeight(); + f->style = font->GetStyle(); + f->stretch = font->GetStretch(); + + queueRedrawSampleText(f); +} + +static void styleEdited(struct fontDialog *f) +{ + if (cbTypeToSelect(f->styleCombobox, &(f->curStyle), FALSE)) + styleChanged(f); +} + +static void familyChanged(struct fontDialog *f) +{ + LRESULT pos; + BOOL selected; + IDWriteFontFamily *family; + IDWriteFont *font, *matchFont; + DWRITE_FONT_WEIGHT weight; + DWRITE_FONT_STYLE style; + DWRITE_FONT_STRETCH stretch; + UINT32 i, n; + UINT32 matching; + WCHAR *label; + HRESULT hr; + + selected = cbGetCurSel(f->familyCombobox, &pos); + if (!selected) // on deselect, do nothing + return; + f->curFamily = pos; + + family = (IDWriteFontFamily *) cbGetItemData(f->familyCombobox, (WPARAM) (f->curFamily)); + + // for the nearest style match + // when we select a new family, we want the nearest style to the previously selected one to be chosen + // this is how the Choose Font sample does it + hr = family->GetFirstMatchingFont( + f->weight, + f->stretch, + f->style, + &matchFont); + if (hr != S_OK) + logHRESULT(L"error finding first matching font to previous style in font dialog", hr); + // we can't just compare pointers; a "newly created" object comes out + // the Choose Font sample appears to do this instead + weight = matchFont->GetWeight(); + style = matchFont->GetStyle(); + stretch = matchFont->GetStretch(); + matchFont->Release(); + + // TODO test mutliple streteches; all the fonts I have have only one stretch value? + wipeStylesBox(f); + n = family->GetFontCount(); + matching = 0; // a safe/suitable default just in case + for (i = 0; i < n; i++) { + hr = family->GetFont(i, &font); + if (hr != S_OK) + logHRESULT(L"error getting font for filling styles box", hr); + label = fontStyleName(f->fc, font); + pos = cbAddString(f->styleCombobox, label); + uiprivFree(label); + cbSetItemData(f->styleCombobox, (WPARAM) pos, (LPARAM) font); + if (font->GetWeight() == weight && + font->GetStyle() == style && + font->GetStretch() == stretch) + matching = i; + } + + // and now, load the match + cbSetCurSel(f->styleCombobox, (WPARAM) matching); + styleChanged(f); +} + +// TODO search language variants like the sample does +static void familyEdited(struct fontDialog *f) +{ + if (cbTypeToSelect(f->familyCombobox, &(f->curFamily), FALSE)) + familyChanged(f); +} + +static const struct { + const WCHAR *text; + double value; +} defaultSizes[] = { + { L"8", 8 }, + { L"9", 9 }, + { L"10", 10 }, + { L"11", 11 }, + { L"12", 12 }, + { L"14", 14 }, + { L"16", 16 }, + { L"18", 18 }, + { L"20", 20 }, + { L"22", 22 }, + { L"24", 24 }, + { L"26", 26 }, + { L"28", 28 }, + { L"36", 36 }, + { L"48", 48 }, + { L"72", 72 }, + { NULL, 0 }, +}; + +static void sizeChanged(struct fontDialog *f) +{ + LRESULT pos; + BOOL selected; + + selected = cbGetCurSel(f->sizeCombobox, &pos); + if (!selected) // on deselect, do nothing + return; + f->curSize = defaultSizes[pos].value; + queueRedrawSampleText(f); +} + +static void sizeEdited(struct fontDialog *f) +{ + WCHAR *wsize; + double size; + + // handle type-to-selection + if (cbTypeToSelect(f->sizeCombobox, NULL, FALSE)) { + sizeChanged(f); + return; + } + // selection not chosen, try to parse the typing + wsize = windowText(f->sizeCombobox); + // this is what the Choose Font dialog does; it swallows errors while the real ChooseFont() is not lenient (and only checks on OK) + size = wcstod(wsize, NULL); + // TODO free wsize? I forget already + if (size <= 0) // don't change on invalid size + return; + f->curSize = size; + queueRedrawSampleText(f); +} + +static void fontDialogDrawSampleText(struct fontDialog *f, ID2D1RenderTarget *rt) +{ + D2D1_COLOR_F color; + D2D1_BRUSH_PROPERTIES props; + ID2D1SolidColorBrush *black; + IDWriteFont *font; + IDWriteLocalizedStrings *sampleStrings; + BOOL exists; + WCHAR *sample; + WCHAR *family; + IDWriteTextFormat *format; + D2D1_RECT_F rect; + HRESULT hr; + + color.r = 0.0; + color.g = 0.0; + color.b = 0.0; + color.a = 1.0; + ZeroMemory(&props, sizeof (D2D1_BRUSH_PROPERTIES)); + props.opacity = 1.0; + // identity matrix + props.transform._11 = 1; + props.transform._22 = 1; + hr = rt->CreateSolidColorBrush( + &color, + &props, + &black); + if (hr != S_OK) + logHRESULT(L"error creating solid brush", hr); + + font = (IDWriteFont *) cbGetItemData(f->styleCombobox, (WPARAM) f->curStyle); + hr = font->GetInformationalStrings(DWRITE_INFORMATIONAL_STRING_SAMPLE_TEXT, &sampleStrings, &exists); + if (hr != S_OK) + exists = FALSE; + if (exists) { + sample = uiprivFontCollectionCorrectString(f->fc, sampleStrings); + sampleStrings->Release(); + } else + sample = (WCHAR *) L"The quick brown fox jumps over the lazy dog."; // TODO + + // DirectWrite doesn't allow creating a text format from a font; we need to get this ourselves + family = cbGetItemText(f->familyCombobox, f->curFamily); + hr = dwfactory->CreateTextFormat(family, + NULL, + font->GetWeight(), + font->GetStyle(), + font->GetStretch(), + // typographic points are 1/72 inch; this parameter is 1/96 inch + // fortunately Microsoft does this too, in https://msdn.microsoft.com/en-us/library/windows/desktop/dd371554%28v=vs.85%29.aspx + f->curSize * (96.0 / 72.0), + // see http://stackoverflow.com/questions/28397971/idwritefactorycreatetextformat-failing and https://msdn.microsoft.com/en-us/library/windows/desktop/dd368203.aspx + // TODO use the current locale again? + L"", + &format); + if (hr != S_OK) + logHRESULT(L"error creating IDWriteTextFormat", hr); + uiprivFree(family); + + rect.left = 0; + rect.top = 0; + rect.right = realGetSize(rt).width; + rect.bottom = realGetSize(rt).height; + rt->DrawText(sample, wcslen(sample), + format, + &rect, + black, + // TODO really? + D2D1_DRAW_TEXT_OPTIONS_NONE, + DWRITE_MEASURING_MODE_NATURAL); + + format->Release(); + if (exists) + uiprivFree(sample); + black->Release(); +} + +static LRESULT CALLBACK fontDialogSampleSubProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData) +{ + ID2D1RenderTarget *rt; + struct fontDialog *f; + + switch (uMsg) { + case msgD2DScratchPaint: + rt = (ID2D1RenderTarget *) lParam; + f = (struct fontDialog *) dwRefData; + fontDialogDrawSampleText(f, rt); + return 0; + case WM_NCDESTROY: + if (RemoveWindowSubclass(hwnd, fontDialogSampleSubProc, uIdSubclass) == FALSE) + logLastError(L"error removing font dialog sample text subclass"); + break; + } + return DefSubclassProc(hwnd, uMsg, wParam, lParam); +} + +static void setupInitialFontDialogState(struct fontDialog *f) +{ + WCHAR wsize[512]; // this should be way more than enough + LRESULT pos; + + // first let's load the size + // the real font dialog: + // - if the chosen font size is in the list, it selects that item AND makes it topmost + // - if the chosen font size is not in the list, don't bother + // we'll simulate it by setting the text to a %f representation, then pretending as if it was entered + // TODO is 512 the correct number to pass to _snwprintf()? + // TODO will this revert to scientific notation? + _snwprintf(wsize, 512, L"%g", f->params->size); + // TODO make this a setWindowText() + if (SendMessageW(f->sizeCombobox, WM_SETTEXT, 0, (LPARAM) wsize) != (LRESULT) TRUE) + logLastError(L"error setting size combobox to initial font size"); + sizeEdited(f); + if (cbGetCurSel(f->sizeCombobox, &pos)) + if (SendMessageW(f->sizeCombobox, CB_SETTOPINDEX, (WPARAM) pos, 0) != 0) + logLastError(L"error making chosen size topmost in the size combobox"); + + // now we set the family and style + // we do this by first setting the previous style attributes, then simulating a font entered + f->weight = f->params->font->GetWeight(); + f->style = f->params->font->GetStyle(); + f->stretch = f->params->font->GetStretch(); + if (SendMessageW(f->familyCombobox, WM_SETTEXT, 0, (LPARAM) (f->params->familyName)) != (LRESULT) TRUE) + logLastError(L"error setting family combobox to initial font family"); + familyEdited(f); +} + +static struct fontDialog *beginFontDialog(HWND hwnd, LPARAM lParam) +{ + struct fontDialog *f; + UINT32 i, nFamilies; + IDWriteFontFamily *family; + WCHAR *wname; + LRESULT pos; + HWND samplePlacement; + HRESULT hr; + + f = uiprivNew(struct fontDialog); + f->hwnd = hwnd; + f->params = (struct fontDialogParams *) lParam; + + f->familyCombobox = getDlgItem(f->hwnd, rcFontFamilyCombobox); + f->styleCombobox = getDlgItem(f->hwnd, rcFontStyleCombobox); + f->sizeCombobox = getDlgItem(f->hwnd, rcFontSizeCombobox); + + f->fc = uiprivLoadFontCollection(); + nFamilies = f->fc->fonts->GetFontFamilyCount(); + for (i = 0; i < nFamilies; i++) { + hr = f->fc->fonts->GetFontFamily(i, &family); + if (hr != S_OK) + logHRESULT(L"error getting font family", hr); + wname = uiprivFontCollectionFamilyName(f->fc, family); + pos = cbAddString(f->familyCombobox, wname); + uiprivFree(wname); + cbSetItemData(f->familyCombobox, (WPARAM) pos, (LPARAM) family); + } + + for (i = 0; defaultSizes[i].text != NULL; i++) + cbInsertString(f->sizeCombobox, defaultSizes[i].text, (WPARAM) i); + + samplePlacement = getDlgItem(f->hwnd, rcFontSamplePlacement); + uiWindowsEnsureGetWindowRect(samplePlacement, &(f->sampleRect)); + mapWindowRect(NULL, f->hwnd, &(f->sampleRect)); + uiWindowsEnsureDestroyWindow(samplePlacement); + f->sampleBox = newD2DScratch(f->hwnd, &(f->sampleRect), (HMENU) rcFontSamplePlacement, fontDialogSampleSubProc, (DWORD_PTR) f); + + setupInitialFontDialogState(f); + return f; +} + +static void endFontDialog(struct fontDialog *f, INT_PTR code) +{ + wipeStylesBox(f); + cbWipeAndReleaseData(f->familyCombobox); + uiprivFontCollectionFree(f->fc); + if (EndDialog(f->hwnd, code) == 0) + logLastError(L"error ending font dialog"); + uiprivFree(f); +} + +static INT_PTR tryFinishDialog(struct fontDialog *f, WPARAM wParam) +{ + IDWriteFontFamily *family; + + // cancelling + if (LOWORD(wParam) != IDOK) { + endFontDialog(f, 1); + return TRUE; + } + + // OK + uiprivDestroyFontDialogParams(f->params); + f->params->font = (IDWriteFont *) cbGetItemData(f->styleCombobox, f->curStyle); + // we need to save font from being destroyed with the combobox + f->params->font->AddRef(); + f->params->size = f->curSize; + family = (IDWriteFontFamily *) cbGetItemData(f->familyCombobox, f->curFamily); + f->params->familyName = uiprivFontCollectionFamilyName(f->fc, family); + f->params->styleName = fontStyleName(f->fc, f->params->font); + endFontDialog(f, 2); + return TRUE; +} + +static INT_PTR CALLBACK fontDialogDlgProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + struct fontDialog *f; + + f = (struct fontDialog *) GetWindowLongPtrW(hwnd, DWLP_USER); + if (f == NULL) { + if (uMsg == WM_INITDIALOG) { + f = beginFontDialog(hwnd, lParam); + SetWindowLongPtrW(hwnd, DWLP_USER, (LONG_PTR) f); + return TRUE; + } + return FALSE; + } + + switch (uMsg) { + case WM_COMMAND: + SetWindowLongPtrW(f->hwnd, DWLP_MSGRESULT, 0); // just in case + switch (LOWORD(wParam)) { + case IDOK: + case IDCANCEL: + if (HIWORD(wParam) != BN_CLICKED) + return FALSE; + return tryFinishDialog(f, wParam); + case rcFontFamilyCombobox: + if (HIWORD(wParam) == CBN_SELCHANGE) { + familyChanged(f); + return TRUE; + } + if (HIWORD(wParam) == CBN_EDITCHANGE) { + familyEdited(f); + return TRUE; + } + return FALSE; + case rcFontStyleCombobox: + if (HIWORD(wParam) == CBN_SELCHANGE) { + styleChanged(f); + return TRUE; + } + if (HIWORD(wParam) == CBN_EDITCHANGE) { + styleEdited(f); + return TRUE; + } + return FALSE; + case rcFontSizeCombobox: + if (HIWORD(wParam) == CBN_SELCHANGE) { + sizeChanged(f); + return TRUE; + } + if (HIWORD(wParam) == CBN_EDITCHANGE) { + sizeEdited(f); + return TRUE; + } + return FALSE; + } + return FALSE; + } + return FALSE; +} + +// because Windows doesn't really support resources in static libraries, we have to embed this directly; oh well +/* +// this is for our custom DirectWrite-based font dialog (see fontdialog.cpp) +// this is based on the "New Font Dialog with Syslink" in Microsoft's font.dlg +// LONGTERM look at localization +// LONGTERM make it look tighter and nicer like the real one, including the actual heights of the font family and style comboboxes +rcFontDialog DIALOGEX 13, 54, 243, 200 +STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU | DS_3DLOOK +CAPTION "Font" +FONT 9, "Segoe UI" +BEGIN + LTEXT "&Font:", -1, 7, 7, 98, 9 + COMBOBOX rcFontFamilyCombobox, 7, 16, 98, 76, + CBS_SIMPLE | CBS_AUTOHSCROLL | CBS_DISABLENOSCROLL | + CBS_SORT | WS_VSCROLL | WS_TABSTOP | CBS_HASSTRINGS + + LTEXT "Font st&yle:", -1, 114, 7, 74, 9 + COMBOBOX rcFontStyleCombobox, 114, 16, 74, 76, + CBS_SIMPLE | CBS_AUTOHSCROLL | CBS_DISABLENOSCROLL | + WS_VSCROLL | WS_TABSTOP | CBS_HASSTRINGS + + LTEXT "&Size:", -1, 198, 7, 36, 9 + COMBOBOX rcFontSizeCombobox, 198, 16, 36, 76, + CBS_SIMPLE | CBS_AUTOHSCROLL | CBS_DISABLENOSCROLL | + CBS_SORT | WS_VSCROLL | WS_TABSTOP | CBS_HASSTRINGS + + GROUPBOX "Sample", -1, 7, 97, 227, 70, WS_GROUP + CTEXT "AaBbYyZz", rcFontSamplePlacement, 9, 106, 224, 60, SS_NOPREFIX | NOT WS_VISIBLE + + DEFPUSHBUTTON "OK", IDOK, 141, 181, 45, 14, WS_GROUP + PUSHBUTTON "Cancel", IDCANCEL, 190, 181, 45, 14, WS_GROUP +END +*/ +static const uint8_t data_rcFontDialog[] = { + 0x01, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xC4, 0x00, 0xC8, 0x80, + 0x0A, 0x00, 0x0D, 0x00, 0x36, 0x00, 0xF3, 0x00, + 0xC8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x00, + 0x6F, 0x00, 0x6E, 0x00, 0x74, 0x00, 0x00, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x00, 0x01, 0x53, 0x00, + 0x65, 0x00, 0x67, 0x00, 0x6F, 0x00, 0x65, 0x00, + 0x20, 0x00, 0x55, 0x00, 0x49, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x02, 0x50, 0x07, 0x00, 0x07, 0x00, + 0x62, 0x00, 0x09, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0x82, 0x00, 0x26, 0x00, 0x46, 0x00, + 0x6F, 0x00, 0x6E, 0x00, 0x74, 0x00, 0x3A, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x41, 0x0B, 0x21, 0x50, + 0x07, 0x00, 0x10, 0x00, 0x62, 0x00, 0x4C, 0x00, + 0xE8, 0x03, 0x00, 0x00, 0xFF, 0xFF, 0x85, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x50, + 0x72, 0x00, 0x07, 0x00, 0x4A, 0x00, 0x09, 0x00, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x82, 0x00, + 0x46, 0x00, 0x6F, 0x00, 0x6E, 0x00, 0x74, 0x00, + 0x20, 0x00, 0x73, 0x00, 0x74, 0x00, 0x26, 0x00, + 0x79, 0x00, 0x6C, 0x00, 0x65, 0x00, 0x3A, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x41, 0x0A, 0x21, 0x50, + 0x72, 0x00, 0x10, 0x00, 0x4A, 0x00, 0x4C, 0x00, + 0xE9, 0x03, 0x00, 0x00, 0xFF, 0xFF, 0x85, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x50, + 0xC6, 0x00, 0x07, 0x00, 0x24, 0x00, 0x09, 0x00, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x82, 0x00, + 0x26, 0x00, 0x53, 0x00, 0x69, 0x00, 0x7A, 0x00, + 0x65, 0x00, 0x3A, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x41, 0x0B, 0x21, 0x50, 0xC6, 0x00, 0x10, 0x00, + 0x24, 0x00, 0x4C, 0x00, 0xEA, 0x03, 0x00, 0x00, + 0xFF, 0xFF, 0x85, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x07, 0x00, 0x02, 0x50, 0x07, 0x00, 0x61, 0x00, + 0xE3, 0x00, 0x46, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0x80, 0x00, 0x53, 0x00, 0x61, 0x00, + 0x6D, 0x00, 0x70, 0x00, 0x6C, 0x00, 0x65, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x81, 0x00, 0x02, 0x40, + 0x09, 0x00, 0x6A, 0x00, 0xE0, 0x00, 0x3C, 0x00, + 0xEB, 0x03, 0x00, 0x00, 0xFF, 0xFF, 0x82, 0x00, + 0x41, 0x00, 0x61, 0x00, 0x42, 0x00, 0x62, 0x00, + 0x59, 0x00, 0x79, 0x00, 0x5A, 0x00, 0x7A, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x50, + 0x8D, 0x00, 0xB5, 0x00, 0x2D, 0x00, 0x0E, 0x00, + 0x01, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x80, 0x00, + 0x4F, 0x00, 0x4B, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x03, 0x50, 0xBE, 0x00, 0xB5, 0x00, + 0x2D, 0x00, 0x0E, 0x00, 0x02, 0x00, 0x00, 0x00, + 0xFF, 0xFF, 0x80, 0x00, 0x43, 0x00, 0x61, 0x00, + 0x6E, 0x00, 0x63, 0x00, 0x65, 0x00, 0x6C, 0x00, + 0x00, 0x00, 0x00, 0x00, +}; +static_assert(ARRAYSIZE(data_rcFontDialog) == 476, "wrong size for resource rcFontDialog"); + +BOOL uiprivShowFontDialog(HWND parent, struct fontDialogParams *params) +{ + switch (DialogBoxIndirectParamW(hInstance, (const DLGTEMPLATE *) data_rcFontDialog, parent, fontDialogDlgProc, (LPARAM) params)) { + case 1: // cancel + return FALSE; + case 2: // ok + // make the compiler happy by putting the return after the switch + break; + default: + logLastError(L"error running font dialog"); + } + return TRUE; +} + +static IDWriteFontFamily *tryFindFamily(IDWriteFontCollection *fc, const WCHAR *name) +{ + UINT32 index; + BOOL exists; + IDWriteFontFamily *family; + HRESULT hr; + + hr = fc->FindFamilyName(name, &index, &exists); + if (hr != S_OK) + logHRESULT(L"error finding font family for font dialog", hr); + if (!exists) + return NULL; + hr = fc->GetFontFamily(index, &family); + if (hr != S_OK) + logHRESULT(L"error extracting found font family for font dialog", hr); + return family; +} + +void uiprivLoadInitialFontDialogParams(struct fontDialogParams *params) +{ + struct fontCollection *fc; + IDWriteFontFamily *family; + IDWriteFont *font; + HRESULT hr; + + // Our preferred font is Arial 10 Regular. + // 10 comes from the official font dialog. + // Arial Regular is a reasonable, if arbitrary, default; it's similar to the defaults on other systems. + // If Arial isn't found, we'll use Helvetica and then MS Sans Serif as fallbacks, and if not, we'll just grab the first font family in the collection. + + // We need the correct localized name for Regular (and possibly Arial too? let's say yes to be safe), so let's grab the strings from DirectWrite instead of hardcoding them. + fc = uiprivLoadFontCollection(); + family = tryFindFamily(fc->fonts, L"Arial"); + if (family == NULL) { + family = tryFindFamily(fc->fonts, L"Helvetica"); + if (family == NULL) { + family = tryFindFamily(fc->fonts, L"MS Sans Serif"); + if (family == NULL) { + hr = fc->fonts->GetFontFamily(0, &family); + if (hr != S_OK) + logHRESULT(L"error getting first font out of font collection (worst case scenario)", hr); + } + } + } + + // next part is simple: just get the closest match to regular + hr = family->GetFirstMatchingFont( + DWRITE_FONT_WEIGHT_NORMAL, + DWRITE_FONT_STRETCH_NORMAL, + DWRITE_FONT_STYLE_NORMAL, + &font); + if (hr != S_OK) + logHRESULT(L"error getting Regular font from Arial", hr); + + params->font = font; + params->size = 10; + params->familyName = uiprivFontCollectionFamilyName(fc, family); + params->styleName = fontStyleName(fc, font); + + // don't release font; we still need it + family->Release(); + uiprivFontCollectionFree(fc); +} + +void uiprivDestroyFontDialogParams(struct fontDialogParams *params) +{ + params->font->Release(); + uiprivFree(params->familyName); + uiprivFree(params->styleName); +} + +WCHAR *uiprivFontDialogParamsToString(struct fontDialogParams *params) +{ + WCHAR *text; + + // TODO dynamically allocate + text = (WCHAR *) uiprivAlloc(512 * sizeof (WCHAR), "WCHAR[]"); + _snwprintf(text, 512, L"%s %s %g", + params->familyName, + params->styleName, + params->size); + return text; +} diff --git a/dep/libui/windows/fontmatch.cpp b/dep/libui/windows/fontmatch.cpp new file mode 100644 index 0000000..73f2954 --- /dev/null +++ b/dep/libui/windows/fontmatch.cpp @@ -0,0 +1,61 @@ +// 11 march 2018 +#include "uipriv_windows.hpp" +#include "attrstr.hpp" + +// TODO should be const but then I can't operator[] on it; the real solution is to find a way to do designated array initializers in C++11 but I do not know enough C++ voodoo to make it work (it is possible but no one else has actually done it before) +static std::map dwriteItalics = { + { uiTextItalicNormal, DWRITE_FONT_STYLE_NORMAL }, + { uiTextItalicOblique, DWRITE_FONT_STYLE_OBLIQUE }, + { uiTextItalicItalic, DWRITE_FONT_STYLE_ITALIC }, +}; + +// TODO should be const but then I can't operator[] on it; the real solution is to find a way to do designated array initializers in C++11 but I do not know enough C++ voodoo to make it work (it is possible but no one else has actually done it before) +static std::map dwriteStretches = { + { uiTextStretchUltraCondensed, DWRITE_FONT_STRETCH_ULTRA_CONDENSED }, + { uiTextStretchExtraCondensed, DWRITE_FONT_STRETCH_EXTRA_CONDENSED }, + { uiTextStretchCondensed, DWRITE_FONT_STRETCH_CONDENSED }, + { uiTextStretchSemiCondensed, DWRITE_FONT_STRETCH_SEMI_CONDENSED }, + { uiTextStretchNormal, DWRITE_FONT_STRETCH_NORMAL }, + { uiTextStretchSemiExpanded, DWRITE_FONT_STRETCH_SEMI_EXPANDED }, + { uiTextStretchExpanded, DWRITE_FONT_STRETCH_EXPANDED }, + { uiTextStretchExtraExpanded, DWRITE_FONT_STRETCH_EXTRA_EXPANDED }, + { uiTextStretchUltraExpanded, DWRITE_FONT_STRETCH_ULTRA_EXPANDED }, +}; + +// for the most part, DirectWrite weights correlate to ours +// the differences: +// - Minimum — libui: 0, DirectWrite: 1 +// - Maximum — libui: 1000, DirectWrite: 999 +// TODO figure out what to do about this shorter range (the actual major values are the same (but with different names), so it's just a range issue) +DWRITE_FONT_WEIGHT uiprivWeightToDWriteWeight(uiTextWeight w) +{ + return (DWRITE_FONT_WEIGHT) w; +} + +DWRITE_FONT_STYLE uiprivItalicToDWriteStyle(uiTextItalic i) +{ + return dwriteItalics[i]; +} + +DWRITE_FONT_STRETCH uiprivStretchToDWriteStretch(uiTextStretch s) +{ + return dwriteStretches[s]; +} + +void uiprivFontDescriptorFromIDWriteFont(IDWriteFont *font, uiFontDescriptor *uidesc) +{ + DWRITE_FONT_STYLE dwitalic; + DWRITE_FONT_STRETCH dwstretch; + + dwitalic = font->GetStyle(); + // TODO reverse the above misalignment if it is corrected + uidesc->Weight = (uiTextWeight) (font->GetWeight()); + dwstretch = font->GetStretch(); + + for (uidesc->Italic = uiTextItalicNormal; uidesc->Italic < uiTextItalicItalic; uidesc->Italic++) + if (dwriteItalics[uidesc->Italic] == dwitalic) + break; + for (uidesc->Stretch = uiTextStretchUltraCondensed; uidesc->Stretch < uiTextStretchUltraExpanded; uidesc->Stretch++) + if (dwriteStretches[uidesc->Stretch] == dwstretch) + break; +} diff --git a/dep/libui/windows/form.cpp b/dep/libui/windows/form.cpp new file mode 100644 index 0000000..ed19467 --- /dev/null +++ b/dep/libui/windows/form.cpp @@ -0,0 +1,319 @@ +// 8 june 2016 +#include "uipriv_windows.hpp" + +struct formChild { + uiControl *c; + HWND label; + int stretchy; + int height; +}; + +struct uiForm { + uiWindowsControl c; + HWND hwnd; + std::vector *controls; + int padded; +}; + +static void formPadding(uiForm *f, int *xpadding, int *ypadding) +{ + uiWindowsSizing sizing; + + *xpadding = 0; + *ypadding = 0; + if (f->padded) { + uiWindowsGetSizing(f->hwnd, &sizing); + uiWindowsSizingStandardPadding(&sizing, xpadding, ypadding); + } +} + +// via http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing +#define labelHeight 8 +#define labelYOffset 3 + +static void formRelayout(uiForm *f) +{ + RECT r; + int x, y, width, height; + int xpadding, ypadding; + int nStretchy; + int labelwid, stretchyht; + int thiswid; + int i; + int minimumWidth, minimumHeight; + uiWindowsSizing sizing; + int labelht, labelyoff; + int nVisible; + + if (f->controls->size() == 0) + return; + + uiWindowsEnsureGetClientRect(f->hwnd, &r); + x = r.left; + y = r.top; + width = r.right - r.left; + height = r.bottom - r.top; + + // 0) get this Form's padding + formPadding(f, &xpadding, &ypadding); + + // 1) get width of labels and height of non-stretchy controls + // this will tell us how much space will be left for controls + labelwid = 0; + stretchyht = height; + nStretchy = 0; + nVisible = 0; + for (struct formChild &fc : *(f->controls)) { + if (!uiControlVisible(fc.c)) { + ShowWindow(fc.label, SW_HIDE); + continue; + } + ShowWindow(fc.label, SW_SHOW); + nVisible++; + thiswid = uiWindowsWindowTextWidth(fc.label); + if (labelwid < thiswid) + labelwid = thiswid; + if (fc.stretchy) { + nStretchy++; + continue; + } + uiWindowsControlMinimumSize(uiWindowsControl(fc.c), &minimumWidth, &minimumHeight); + fc.height = minimumHeight; + stretchyht -= minimumHeight; + } + if (nVisible == 0) // nothing to do + return; + + // 2) inset the available rect by the needed padding + width -= xpadding; + height -= (nVisible - 1) * ypadding; + stretchyht -= (nVisible - 1) * ypadding; + + // 3) now get the width of controls and the height of stretchy controls + width -= labelwid; + if (nStretchy != 0) { + stretchyht /= nStretchy; + for (struct formChild &fc : *(f->controls)) { + if (!uiControlVisible(fc.c)) + continue; + if (fc.stretchy) + fc.height = stretchyht; + } + } + + // 4) get the y offset + labelyoff = labelYOffset; + uiWindowsGetSizing(f->hwnd, &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, NULL, &labelyoff); + + // 5) now we can position controls + // first, make relative to the top-left corner of the container + // also prefer left alignment on Windows + x = labelwid + xpadding; + y = 0; + for (const struct formChild &fc : *(f->controls)) { + if (!uiControlVisible(fc.c)) + continue; + labelht = labelHeight; + uiWindowsGetSizing(f->hwnd, &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, NULL, &labelht); + uiWindowsEnsureMoveWindowDuringResize(fc.label, 0, y + labelyoff - sizing.InternalLeading, labelwid, labelht); + uiWindowsEnsureMoveWindowDuringResize((HWND) uiControlHandle(fc.c), x, y, width, fc.height); + y += fc.height + ypadding; + } +} + +static void uiFormDestroy(uiControl *c) +{ + uiForm *f = uiForm(c); + + for (const struct formChild &fc : *(f->controls)) { + uiControlSetParent(fc.c, NULL); + uiControlDestroy(fc.c); + uiWindowsEnsureDestroyWindow(fc.label); + } + delete f->controls; + uiWindowsEnsureDestroyWindow(f->hwnd); + uiFreeControl(uiControl(f)); +} + +uiWindowsControlDefaultHandle(uiForm) +uiWindowsControlDefaultParent(uiForm) +uiWindowsControlDefaultSetParent(uiForm) +uiWindowsControlDefaultToplevel(uiForm) +uiWindowsControlDefaultVisible(uiForm) +uiWindowsControlDefaultShow(uiForm) +uiWindowsControlDefaultHide(uiForm) +uiWindowsControlDefaultEnabled(uiForm) +uiWindowsControlDefaultEnable(uiForm) +uiWindowsControlDefaultDisable(uiForm) + +static void uiFormSyncEnableState(uiWindowsControl *c, int enabled) +{ + uiForm *f = uiForm(c); + + if (uiWindowsShouldStopSyncEnableState(uiWindowsControl(f), enabled)) + return; + for (const struct formChild &fc : *(f->controls)) + uiWindowsControlSyncEnableState(uiWindowsControl(fc.c), enabled); +} + +uiWindowsControlDefaultSetParentHWND(uiForm) + +static void uiFormMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + uiForm *f = uiForm(c); + int xpadding, ypadding; + int nStretchy; + // these two contain the largest minimum width and height of all stretchy controls in the form + // all stretchy controls will use this value to determine the final minimum size + int maxLabelWidth, maxControlWidth; + int maxStretchyHeight; + int labelwid; + int i; + int minimumWidth, minimumHeight; + int nVisible; + uiWindowsSizing sizing; + + *width = 0; + *height = 0; + if (f->controls->size() == 0) + return; + + // 0) get this Form's padding + formPadding(f, &xpadding, &ypadding); + + // 1) determine the longest width of all controls and labels; add in the height of non-stretchy controls and get (but not add in) the largest heights of stretchy controls + // we still add in like direction of stretchy controls + nStretchy = 0; + maxLabelWidth = 0; + maxControlWidth = 0; + maxStretchyHeight = 0; + nVisible = 0; + for (const struct formChild &fc : *(f->controls)) { + if (!uiControlVisible(fc.c)) + continue; + nVisible++; + labelwid = uiWindowsWindowTextWidth(fc.label); + if (maxLabelWidth < labelwid) + maxLabelWidth = labelwid; + uiWindowsControlMinimumSize(uiWindowsControl(fc.c), &minimumWidth, &minimumHeight); + if (fc.stretchy) { + nStretchy++; + if (maxStretchyHeight < minimumHeight) + maxStretchyHeight = minimumHeight; + } + if (maxControlWidth < minimumWidth) + maxControlWidth = minimumWidth; + if (!fc.stretchy) + *height += minimumHeight; + } + if (nVisible == 0) // nothing to show; return 0x0 + return; + *width += maxLabelWidth + maxControlWidth; + + // 2) outset the desired rect with the needed padding + *width += xpadding; + *height += (nVisible - 1) * ypadding; + + // 3) and now we can add in stretchy controls + *height += nStretchy * maxStretchyHeight; +} + +static void uiFormMinimumSizeChanged(uiWindowsControl *c) +{ + uiForm *f = uiForm(c); + + if (uiWindowsControlTooSmall(uiWindowsControl(f))) { + uiWindowsControlContinueMinimumSizeChanged(uiWindowsControl(f)); + return; + } + formRelayout(f); +} + +uiWindowsControlDefaultLayoutRect(uiForm) +uiWindowsControlDefaultAssignControlIDZOrder(uiForm) + +static void uiFormChildVisibilityChanged(uiWindowsControl *c) +{ + // TODO eliminate the redundancy + uiWindowsControlMinimumSizeChanged(c); +} + +static void formArrangeChildren(uiForm *f) +{ + LONG_PTR controlID; + HWND insertAfter; + int i; + + controlID = 100; + insertAfter = NULL; + for (const struct formChild &fc : *(f->controls)) { + // TODO assign label ID and z-order + uiWindowsControlAssignControlIDZOrder(uiWindowsControl(fc.c), &controlID, &insertAfter); + } +} + +void uiFormAppend(uiForm *f, const char *label, uiControl *c, int stretchy) +{ + struct formChild fc; + WCHAR *wlabel; + + fc.c = c; + wlabel = toUTF16(label); + fc.label = uiWindowsEnsureCreateControlHWND(0, + L"STATIC", wlabel, + SS_LEFT | SS_NOPREFIX, + hInstance, NULL, + TRUE); + uiprivFree(wlabel); + uiWindowsEnsureSetParentHWND(fc.label, f->hwnd); + fc.stretchy = stretchy; + uiControlSetParent(fc.c, uiControl(f)); + uiWindowsControlSetParentHWND(uiWindowsControl(fc.c), f->hwnd); + f->controls->push_back(fc); + formArrangeChildren(f); + uiWindowsControlMinimumSizeChanged(uiWindowsControl(f)); +} + +void uiFormDelete(uiForm *f, int index) +{ + struct formChild fc; + + fc = (*(f->controls))[index]; + uiControlSetParent(fc.c, NULL); + uiWindowsControlSetParentHWND(uiWindowsControl(fc.c), NULL); + uiWindowsEnsureDestroyWindow(fc.label); + f->controls->erase(f->controls->begin() + index); + formArrangeChildren(f); + uiWindowsControlMinimumSizeChanged(uiWindowsControl(f)); +} + +int uiFormPadded(uiForm *f) +{ + return f->padded; +} + +void uiFormSetPadded(uiForm *f, int padded) +{ + f->padded = padded; + uiWindowsControlMinimumSizeChanged(uiWindowsControl(f)); +} + +static void onResize(uiWindowsControl *c) +{ + formRelayout(uiForm(c)); +} + +uiForm *uiNewForm(void) +{ + uiForm *f; + + uiWindowsNewControl(uiForm, f); + + f->hwnd = uiWindowsMakeContainer(uiWindowsControl(f), onResize); + + f->controls = new std::vector; + + return f; +} diff --git a/dep/libui/windows/graphemes.cpp b/dep/libui/windows/graphemes.cpp new file mode 100644 index 0000000..c11dd20 --- /dev/null +++ b/dep/libui/windows/graphemes.cpp @@ -0,0 +1,60 @@ +// 25 may 2016 +#include "uipriv_windows.hpp" +#include "attrstr.hpp" + +// We could use CharNextW() to generate grapheme cluster boundaries, but it doesn't handle surrogate pairs properly (see http://archives.miloush.net/michkap/archive/2008/12/16/9223301.html). +// We could also use Uniscribe (see http://archives.miloush.net/michkap/archive/2005/01/14/352802.html, http://www.catch22.net/tuts/uniscribe-mysteries, http://www.catch22.net/tuts/keyboard-navigation, and https://maxradi.us/documents/uniscribe/), but its rules for buffer sizes is convoluted. +// Let's just deal with the CharNextW() bug. + +int uiprivGraphemesTakesUTF16(void) +{ + return 1; +} + +uiprivGraphemes *uiprivNewGraphemes(void *s, size_t len) +{ + uiprivGraphemes *g; + WCHAR *str; + size_t *pPTG, *pGTP; + + g = uiprivNew(uiprivGraphemes); + + g->len = 0; + str = (WCHAR *) s; + while (*str != L'\0') { + g->len++; + str = CharNextW(str); + // no need to worry about surrogates if we're just counting + } + + g->pointsToGraphemes = (size_t *) uiprivAlloc((len + 1) * sizeof (size_t), "size_t[] (graphemes)"); + g->graphemesToPoints = (size_t *) uiprivAlloc((g->len + 1) * sizeof (size_t), "size_t[] (graphemes)"); + + pPTG = g->pointsToGraphemes; + pGTP = g->graphemesToPoints; + str = (WCHAR *) s; + while (*str != L'\0') { + WCHAR *next, *p; + ptrdiff_t nextoff; + + // as part of the bug, we need to make sure we only call CharNextW() on low halves, otherwise it'll return the same low half forever + nextoff = 0; + if (IS_HIGH_SURROGATE(*str)) + nextoff = 1; + next = CharNextW(str + nextoff); + if (IS_LOW_SURROGATE(*next)) + next--; + + *pGTP = pPTG - g->pointsToGraphemes; + for (p = str; p < next; p++) + *pPTG++ = pGTP - g->graphemesToPoints; + pGTP++; + + str = next; + } + // and handle the last item for the end of the string + *pGTP = pPTG - g->pointsToGraphemes; + *pPTG = pGTP - g->graphemesToPoints; + + return g; +} diff --git a/dep/libui/windows/grid.cpp b/dep/libui/windows/grid.cpp new file mode 100644 index 0000000..cac87af --- /dev/null +++ b/dep/libui/windows/grid.cpp @@ -0,0 +1,658 @@ +// 10 june 2016 +#include "uipriv_windows.hpp" + +// TODO compare with GTK+: +// - what happens if you call InsertAt() twice? +// - what happens if you call Append() twice? + +// TODOs +// - the Assorted page has clipping and repositioning issues + +struct gridChild { + uiControl *c; + int left; + int top; + int xspan; + int yspan; + int hexpand; + uiAlign halign; + int vexpand; + uiAlign valign; + + // have these here so they don't need to be reallocated each relayout + int finalx, finaly; + int finalwidth, finalheight; + int minwidth, minheight; +}; + +struct uiGrid { + uiWindowsControl c; + HWND hwnd; + std::vector *children; + std::map *indexof; + int padded; + + int xmin, ymin; + int xmax, ymax; +}; + +static bool gridRecomputeMinMax(uiGrid *g) +{ + bool first = true; + + for (struct gridChild *gc : *(g->children)) { + // this is important; we want g->xmin/g->ymin to satisfy gridLayoutData::visibleRow()/visibleColumn() + if (!uiControlVisible(gc->c)) + continue; + if (first) { + g->xmin = gc->left; + g->ymin = gc->top; + g->xmax = gc->left + gc->xspan; + g->ymax = gc->top + gc->yspan; + first = false; + continue; + } + if (g->xmin > gc->left) + g->xmin = gc->left; + if (g->ymin > gc->top) + g->ymin = gc->top; + if (g->xmax < (gc->left + gc->xspan)) + g->xmax = gc->left + gc->xspan; + if (g->ymax < (gc->top + gc->yspan)) + g->ymax = gc->top + gc->yspan; + } + return first != false; +} + +#define xcount(g) ((g)->xmax - (g)->xmin) +#define ycount(g) ((g)->ymax - (g)->ymin) +#define toxindex(g, x) ((x) - (g)->xmin) +#define toyindex(g, y) ((y) - (g)->ymin) + +class gridLayoutData { + int ycount; +public: + int **gg; // topological map gg[y][x] = control index + int *colwidths; + int *rowheights; + bool *hexpand; + bool *vexpand; + int nVisibleRows; + int nVisibleColumns; + + bool noVisible; + + gridLayoutData(uiGrid *g) + { + size_t i; + int x, y; + + this->noVisible = gridRecomputeMinMax(g); + + this->gg = new int *[ycount(g)]; + for (y = 0; y < ycount(g); y++) { + this->gg[y] = new int[xcount(g)]; + for (x = 0; x < xcount(g); x++) + this->gg[y][x] = -1; + } + + for (i = 0; i < g->children->size(); i++) { + struct gridChild *gc; + + gc = (*(g->children))[i]; + if (!uiControlVisible(gc->c)) + continue; + for (y = gc->top; y < gc->top + gc->yspan; y++) + for (x = gc->left; x < gc->left + gc->xspan; x++) + this->gg[toyindex(g, y)][toxindex(g, x)] = i; + } + + this->colwidths = new int[xcount(g)]; + ZeroMemory(this->colwidths, xcount(g) * sizeof (int)); + this->rowheights = new int[ycount(g)]; + ZeroMemory(this->rowheights, ycount(g) * sizeof (int)); + this->hexpand = new bool[xcount(g)]; + ZeroMemory(this->hexpand, xcount(g) * sizeof (bool)); + this->vexpand = new bool[ycount(g)]; + ZeroMemory(this->vexpand, ycount(g) * sizeof (bool)); + + this->ycount = ycount(g); + + // if a row or column only contains emptys and spanning cells of a opposite-direction spannings, it is invisible and should not be considered for padding amount calculations + // note that the first row and column will always be visible because gridRecomputeMinMax() computed a smallest fitting rectangle + if (this->noVisible) + return; + this->nVisibleRows = 0; + for (y = 0; y < this->ycount; y++) + if (this->visibleRow(g, y)) + this->nVisibleRows++; + this->nVisibleColumns = 0; + for (x = 0; x < xcount(g); x++) + if (this->visibleColumn(g, x)) + this->nVisibleColumns++; + } + + ~gridLayoutData() + { + size_t y; + + delete[] this->hexpand; + delete[] this->vexpand; + delete[] this->colwidths; + delete[] this->rowheights; + for (y = 0; y < this->ycount; y++) + delete[] this->gg[y]; + delete[] this->gg; + } + + bool visibleRow(uiGrid *g, int y) + { + int x; + struct gridChild *gc; + + for (x = 0; x < xcount(g); x++) + if (this->gg[y][x] != -1) { + gc = (*(g->children))[this->gg[y][x]]; + if (gc->yspan == 1 || gc->top - g->ymin == y) + return true; + } + return false; + } + + bool visibleColumn(uiGrid *g, int x) + { + int y; + struct gridChild *gc; + + for (y = 0; y < this->ycount; y++) + if (this->gg[y][x] != -1) { + gc = (*(g->children))[this->gg[y][x]]; + if (gc->xspan == 1 || gc->left - g->xmin == x) + return true; + } + return false; + } +}; + +static void gridPadding(uiGrid *g, int *xpadding, int *ypadding) +{ + uiWindowsSizing sizing; + + *xpadding = 0; + *ypadding = 0; + if (g->padded) { + uiWindowsGetSizing(g->hwnd, &sizing); + uiWindowsSizingStandardPadding(&sizing, xpadding, ypadding); + } +} + +static void gridRelayout(uiGrid *g) +{ + RECT r; + int x, y, width, height; + gridLayoutData *ld; + int xpadding, ypadding; + int ix, iy; + int iwidth, iheight; + int i; + struct gridChild *gc; + int nhexpand, nvexpand; + + if (g->children->size() == 0) + return; // nothing to do + + uiWindowsEnsureGetClientRect(g->hwnd, &r); + x = r.left; + y = r.top; + width = r.right - r.left; + height = r.bottom - r.top; + + gridPadding(g, &xpadding, &ypadding); + ld = new gridLayoutData(g); + if (ld->noVisible) { // nothing to do + delete ld; + return; + } + + // 0) discount padding from width/height + width -= (ld->nVisibleColumns - 1) * xpadding; + height -= (ld->nVisibleRows - 1) * ypadding; + + // 1) compute colwidths and rowheights before handling expansion + // we only count non-spanning controls to avoid weirdness + for (iy = 0; iy < ycount(g); iy++) + for (ix = 0; ix < xcount(g); ix++) { + i = ld->gg[iy][ix]; + if (i == -1) + continue; + gc = (*(g->children))[i]; + uiWindowsControlMinimumSize(uiWindowsControl(gc->c), &iwidth, &iheight); + if (gc->xspan == 1) + if (ld->colwidths[ix] < iwidth) + ld->colwidths[ix] = iwidth; + if (gc->yspan == 1) + if (ld->rowheights[iy] < iheight) + ld->rowheights[iy] = iheight; + // save these for step 6 + gc->minwidth = iwidth; + gc->minheight = iheight; + } + + // 2) figure out which rows/columns expand but not span + // we need to know which expanding rows/columns don't span before we can handle the ones that do + for (i = 0; i < g->children->size(); i++) { + gc = (*(g->children))[i]; + if (!uiControlVisible(gc->c)) + continue; + if (gc->hexpand && gc->xspan == 1) + ld->hexpand[toxindex(g, gc->left)] = true; + if (gc->vexpand && gc->yspan == 1) + ld->vexpand[toyindex(g, gc->top)] = true; + } + + // 3) figure out which rows/columns expand that do span + // the way we handle this is simple: if none of the spanned rows/columns expand, make all rows/columns expand + for (i = 0; i < g->children->size(); i++) { + gc = (*(g->children))[i]; + if (!uiControlVisible(gc->c)) + continue; + if (gc->hexpand && gc->xspan != 1) { + bool doit = true; + + for (ix = gc->left; ix < gc->left + gc->xspan; ix++) + if (ld->hexpand[toxindex(g, ix)]) { + doit = false; + break; + } + if (doit) + for (ix = gc->left; ix < gc->left + gc->xspan; ix++) + ld->hexpand[toxindex(g, ix)] = true; + } + if (gc->vexpand && gc->yspan != 1) { + bool doit = true; + + for (iy = gc->top; iy < gc->top + gc->yspan; iy++) + if (ld->vexpand[toyindex(g, iy)]) { + doit = false; + break; + } + if (doit) + for (iy = gc->top; iy < gc->top + gc->yspan; iy++) + ld->vexpand[toyindex(g, iy)] = true; + } + } + + // 4) compute and assign expanded widths/heights + nhexpand = 0; + nvexpand = 0; + for (i = 0; i < xcount(g); i++) + if (ld->hexpand[i]) + nhexpand++; + else + width -= ld->colwidths[i]; + for (i = 0; i < ycount(g); i++) + if (ld->vexpand[i]) + nvexpand++; + else + height -= ld->rowheights[i]; + for (i = 0; i < xcount(g); i++) + if (ld->hexpand[i]) + ld->colwidths[i] = width / nhexpand; + for (i = 0; i < ycount(g); i++) + if (ld->vexpand[i]) + ld->rowheights[i] = height / nvexpand; + + // 5) reset the final coordinates for the next step + for (i = 0; i < g->children->size(); i++) { + gc = (*(g->children))[i]; + if (!uiControlVisible(gc->c)) + continue; + gc->finalx = 0; + gc->finaly = 0; + gc->finalwidth = 0; + gc->finalheight = 0; + } + + // 6) compute cell positions and sizes + for (iy = 0; iy < ycount(g); iy++) { + int curx; + int prev; + + curx = 0; + prev = -1; + for (ix = 0; ix < xcount(g); ix++) { + if (!ld->visibleColumn(g, ix)) + continue; + i = ld->gg[iy][ix]; + if (i != -1) { + gc = (*(g->children))[i]; + if (iy == toyindex(g, gc->top)) { // don't repeat this step if the control spans vertically + if (i != prev) + gc->finalx = curx; + else + gc->finalwidth += xpadding; + gc->finalwidth += ld->colwidths[ix]; + } + } + curx += ld->colwidths[ix] + xpadding; + prev = i; + } + } + for (ix = 0; ix < xcount(g); ix++) { + int cury; + int prev; + + cury = 0; + prev = -1; + for (iy = 0; iy < ycount(g); iy++) { + if (!ld->visibleRow(g, iy)) + continue; + i = ld->gg[iy][ix]; + if (i != -1) { + gc = (*(g->children))[i]; + if (ix == toxindex(g, gc->left)) { // don't repeat this step if the control spans horizontally + if (i != prev) + gc->finaly = cury; + else + gc->finalheight += ypadding; + gc->finalheight += ld->rowheights[iy]; + } + } + cury += ld->rowheights[iy] + ypadding; + prev = i; + } + } + + // 7) everything as it stands now is set for xalign == Fill yalign == Fill; set the correct alignments + // this is why we saved minwidth/minheight above + for (i = 0; i < g->children->size(); i++) { + gc = (*(g->children))[i]; + if (!uiControlVisible(gc->c)) + continue; + if (gc->halign != uiAlignFill) { + switch (gc->halign) { + case uiAlignEnd: + gc->finalx += gc->finalwidth - gc->minwidth; + break; + case uiAlignCenter: + gc->finalx += (gc->finalwidth - gc->minwidth) / 2; + break; + } + gc->finalwidth = gc->minwidth; // for all three + } + if (gc->valign != uiAlignFill) { + switch (gc->valign) { + case uiAlignEnd: + gc->finaly += gc->finalheight - gc->minheight; + break; + case uiAlignCenter: + gc->finaly += (gc->finalheight - gc->minheight) / 2; + break; + } + gc->finalheight = gc->minheight; // for all three + } + } + + // 8) and FINALLY we resize + for (iy = 0; iy < ycount(g); iy++) + for (ix = 0; ix < xcount(g); ix++) { + i = ld->gg[iy][ix]; + if (i != -1) { // treat empty cells like spaces + gc = (*(g->children))[i]; + uiWindowsEnsureMoveWindowDuringResize( + (HWND) uiControlHandle(gc->c), + gc->finalx,//TODO + x, + gc->finaly,//TODO + y, + gc->finalwidth, + gc->finalheight); + } + } + + delete ld; +} + +static void uiGridDestroy(uiControl *c) +{ + uiGrid *g = uiGrid(c); + + for (struct gridChild *gc : *(g->children)) { + uiControlSetParent(gc->c, NULL); + uiControlDestroy(gc->c); + uiprivFree(gc); + } + delete g->indexof; + delete g->children; + uiWindowsEnsureDestroyWindow(g->hwnd); + uiFreeControl(uiControl(g)); +} + +uiWindowsControlDefaultHandle(uiGrid) +uiWindowsControlDefaultParent(uiGrid) +uiWindowsControlDefaultSetParent(uiGrid) +uiWindowsControlDefaultToplevel(uiGrid) +uiWindowsControlDefaultVisible(uiGrid) +uiWindowsControlDefaultShow(uiGrid) +uiWindowsControlDefaultHide(uiGrid) +uiWindowsControlDefaultEnabled(uiGrid) +uiWindowsControlDefaultEnable(uiGrid) +uiWindowsControlDefaultDisable(uiGrid) + +static void uiGridSyncEnableState(uiWindowsControl *c, int enabled) +{ + uiGrid *g = uiGrid(c); + + if (uiWindowsShouldStopSyncEnableState(uiWindowsControl(g), enabled)) + return; + for (const struct gridChild *gc : *(g->children)) + uiWindowsControlSyncEnableState(uiWindowsControl(gc->c), enabled); +} + +uiWindowsControlDefaultSetParentHWND(uiGrid) + +static void uiGridMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + uiGrid *g = uiGrid(c); + int xpadding, ypadding; + gridLayoutData *ld; + int x, y; + int i; + struct gridChild *gc; + int minwid, minht; + int colwidth, rowheight; + + *width = 0; + *height = 0; + if (g->children->size() == 0) + return; // nothing to do + + gridPadding(g, &xpadding, &ypadding); + ld = new gridLayoutData(g); + if (ld->noVisible) { // nothing to do; return 0x0 + delete ld; + return; + } + + // 1) compute colwidths and rowheights before handling expansion + // TODO put this in its own function (but careful about the spanning calculation in gridRelayout()) + for (y = 0; y < ycount(g); y++) + for (x = 0; x < xcount(g); x++) { + i = ld->gg[y][x]; + if (i == -1) + continue; + gc = (*(g->children))[i]; + uiWindowsControlMinimumSize(uiWindowsControl(gc->c), &minwid, &minht); + // allot equal space in the presence of spanning to keep things sane + if (ld->colwidths[x] < minwid / gc->xspan) + ld->colwidths[x] = minwid / gc->xspan; + if (ld->rowheights[y] < minht / gc->yspan) + ld->rowheights[y] = minht / gc->yspan; + // save these for step 6 + gc->minwidth = minwid; + gc->minheight = minht; + } + + // 2) compute total column width/row height + colwidth = 0; + rowheight = 0; + for (x = 0; x < xcount(g); x++) + colwidth += ld->colwidths[x]; + for (y = 0; y < ycount(g); y++) + rowheight += ld->rowheights[y]; + + // and that's it; just account for padding + *width = colwidth + (ld->nVisibleColumns - 1) * xpadding; + *height = rowheight + (ld->nVisibleRows - 1) * ypadding; +} + +static void uiGridMinimumSizeChanged(uiWindowsControl *c) +{ + uiGrid *g = uiGrid(c); + + if (uiWindowsControlTooSmall(uiWindowsControl(g))) { + uiWindowsControlContinueMinimumSizeChanged(uiWindowsControl(g)); + return; + } + gridRelayout(g); +} + +uiWindowsControlDefaultLayoutRect(uiGrid) +uiWindowsControlDefaultAssignControlIDZOrder(uiGrid) + +static void uiGridChildVisibilityChanged(uiWindowsControl *c) +{ + // TODO eliminate the redundancy + uiWindowsControlMinimumSizeChanged(c); +} + +// must have called gridRecomputeMinMax() first +static void gridArrangeChildren(uiGrid *g) +{ + LONG_PTR controlID; + HWND insertAfter; + gridLayoutData *ld; + bool *visited; + int x, y; + int i; + struct gridChild *gc; + + if (g->children->size() == 0) + return; // nothing to do + ld = new gridLayoutData(g); + controlID = 100; + insertAfter = NULL; + visited = new bool[g->children->size()]; + ZeroMemory(visited, g->children->size() * sizeof (bool)); + for (y = 0; y < ycount(g); y++) + for (x = 0; x < xcount(g); x++) { + i = ld->gg[y][x]; + if (i == -1) + continue; + if (visited[i]) + continue; + visited[i] = true; + gc = (*(g->children))[i]; + uiWindowsControlAssignControlIDZOrder(uiWindowsControl(gc->c), &controlID, &insertAfter); + } + delete[] visited; + delete ld; +} + +static struct gridChild *toChild(uiControl *c, int xspan, int yspan, int hexpand, uiAlign halign, int vexpand, uiAlign valign) +{ + struct gridChild *gc; + + if (xspan < 0) + uiprivUserBug("You cannot have a negative xspan in a uiGrid cell."); + if (yspan < 0) + uiprivUserBug("You cannot have a negative yspan in a uiGrid cell."); + gc = uiprivNew(struct gridChild); + gc->c = c; + gc->xspan = xspan; + gc->yspan = yspan; + gc->hexpand = hexpand; + gc->halign = halign; + gc->vexpand = vexpand; + gc->valign = valign; + return gc; +} + +static void add(uiGrid *g, struct gridChild *gc) +{ + uiControlSetParent(gc->c, uiControl(g)); + uiWindowsControlSetParentHWND(uiWindowsControl(gc->c), g->hwnd); + g->children->push_back(gc); + (*(g->indexof))[gc->c] = g->children->size() - 1; + gridRecomputeMinMax(g); + gridArrangeChildren(g); + uiWindowsControlMinimumSizeChanged(uiWindowsControl(g)); +} + +void uiGridAppend(uiGrid *g, uiControl *c, int left, int top, int xspan, int yspan, int hexpand, uiAlign halign, int vexpand, uiAlign valign) +{ + struct gridChild *gc; + + gc = toChild(c, xspan, yspan, hexpand, halign, vexpand, valign); + gc->left = left; + gc->top = top; + add(g, gc); +} + +// TODO decide what happens if existing is NULL +void uiGridInsertAt(uiGrid *g, uiControl *c, uiControl *existing, uiAt at, int xspan, int yspan, int hexpand, uiAlign halign, int vexpand, uiAlign valign) +{ + struct gridChild *gc; + struct gridChild *other; + + gc = toChild(c, xspan, yspan, hexpand, halign, vexpand, valign); + other = (*(g->children))[(*(g->indexof))[existing]]; + switch (at) { + case uiAtLeading: + gc->left = other->left - gc->xspan; + gc->top = other->top; + break; + case uiAtTop: + gc->left = other->left; + gc->top = other->top - gc->yspan; + break; + case uiAtTrailing: + gc->left = other->left + other->xspan; + gc->top = other->top; + break; + case uiAtBottom: + gc->left = other->left; + gc->top = other->top + other->yspan; + break; + // TODO add error checks to ALL enums + } + add(g, gc); +} + +int uiGridPadded(uiGrid *g) +{ + return g->padded; +} + +void uiGridSetPadded(uiGrid *g, int padded) +{ + g->padded = padded; + uiWindowsControlMinimumSizeChanged(uiWindowsControl(g)); +} + +static void onResize(uiWindowsControl *c) +{ + gridRelayout(uiGrid(c)); +} + +uiGrid *uiNewGrid(void) +{ + uiGrid *g; + + uiWindowsNewControl(uiGrid, g); + + g->hwnd = uiWindowsMakeContainer(uiWindowsControl(g), onResize); + + g->children = new std::vector; + g->indexof = new std::map; + + return g; +} diff --git a/dep/libui/windows/group.cpp b/dep/libui/windows/group.cpp new file mode 100644 index 0000000..1a2cc6e --- /dev/null +++ b/dep/libui/windows/group.cpp @@ -0,0 +1,217 @@ +// 16 may 2015 +#include "uipriv_windows.hpp" + +struct uiGroup { + uiWindowsControl c; + HWND hwnd; + struct uiControl *child; + int margined; +}; + +// from https://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing +#define groupXMargin 6 +#define groupYMarginTop 11 /* note this value /includes/ the groupbox label */ +#define groupYMarginBottom 7 + +// unfortunately because the client area of a groupbox includes the frame and caption text, we have to apply some margins ourselves, even if we don't want "any" +// these were deduced by hand based on the standard DLU conversions; the X and Y top margins are the width and height, respectively, of one character cell +// they can be fine-tuned later +#define groupUnmarginedXMargin 4 +#define groupUnmarginedYMarginTop 8 +#define groupUnmarginedYMarginBottom 3 + +static void groupMargins(uiGroup *g, int *mx, int *mtop, int *mbottom) +{ + uiWindowsSizing sizing; + + *mx = groupUnmarginedXMargin; + *mtop = groupUnmarginedYMarginTop; + *mbottom = groupUnmarginedYMarginBottom; + if (g->margined) { + *mx = groupXMargin; + *mtop = groupYMarginTop; + *mbottom = groupYMarginBottom; + } + uiWindowsGetSizing(g->hwnd, &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, mx, mtop); + uiWindowsSizingDlgUnitsToPixels(&sizing, NULL, mbottom); +} + +static void groupRelayout(uiGroup *g) +{ + RECT r; + int mx, mtop, mbottom; + + if (g->child == NULL) + return; + uiWindowsEnsureGetClientRect(g->hwnd, &r); + groupMargins(g, &mx, &mtop, &mbottom); + r.left += mx; + r.top += mtop; + r.right -= mx; + r.bottom -= mbottom; + uiWindowsEnsureMoveWindowDuringResize((HWND) uiControlHandle(g->child), r.left, r.top, r.right - r.left, r.bottom - r.top); +} + +static void uiGroupDestroy(uiControl *c) +{ + uiGroup *g = uiGroup(c); + + if (g->child != NULL) { + uiControlSetParent(g->child, NULL); + uiControlDestroy(g->child); + } + uiWindowsEnsureDestroyWindow(g->hwnd); + uiFreeControl(uiControl(g)); +} + +uiWindowsControlDefaultHandle(uiGroup) +uiWindowsControlDefaultParent(uiGroup) +uiWindowsControlDefaultSetParent(uiGroup) +uiWindowsControlDefaultToplevel(uiGroup) +uiWindowsControlDefaultVisible(uiGroup) +uiWindowsControlDefaultShow(uiGroup) +uiWindowsControlDefaultHide(uiGroup) +uiWindowsControlDefaultEnabled(uiGroup) +uiWindowsControlDefaultEnable(uiGroup) +uiWindowsControlDefaultDisable(uiGroup) + +static void uiGroupSyncEnableState(uiWindowsControl *c, int enabled) +{ + uiGroup *g = uiGroup(c); + + if (uiWindowsShouldStopSyncEnableState(uiWindowsControl(g), enabled)) + return; + EnableWindow(g->hwnd, enabled); + if (g->child != NULL) + uiWindowsControlSyncEnableState(uiWindowsControl(g->child), enabled); +} + +uiWindowsControlDefaultSetParentHWND(uiGroup) + +static void uiGroupMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + uiGroup *g = uiGroup(c); + int mx, mtop, mbottom; + int labelWidth; + + *width = 0; + *height = 0; + if (g->child != NULL) + uiWindowsControlMinimumSize(uiWindowsControl(g->child), width, height); + labelWidth = uiWindowsWindowTextWidth(g->hwnd); + if (*width < labelWidth) // don't clip the label; it doesn't ellipsize + *width = labelWidth; + groupMargins(g, &mx, &mtop, &mbottom); + *width += 2 * mx; + *height += mtop + mbottom; +} + +static void uiGroupMinimumSizeChanged(uiWindowsControl *c) +{ + uiGroup *g = uiGroup(c); + + if (uiWindowsControlTooSmall(uiWindowsControl(g))) { + uiWindowsControlContinueMinimumSizeChanged(uiWindowsControl(g)); + return; + } + groupRelayout(g); +} + +uiWindowsControlDefaultLayoutRect(uiGroup) +uiWindowsControlDefaultAssignControlIDZOrder(uiGroup) + +static void uiGroupChildVisibilityChanged(uiWindowsControl *c) +{ + // TODO eliminate the redundancy + uiWindowsControlMinimumSizeChanged(c); +} + +char *uiGroupTitle(uiGroup *g) +{ + return uiWindowsWindowText(g->hwnd); +} + +void uiGroupSetTitle(uiGroup *g, const char *text) +{ + uiWindowsSetWindowText(g->hwnd, text); + // changing the text might necessitate a change in the groupbox's size + uiWindowsControlMinimumSizeChanged(uiWindowsControl(g)); +} + +void uiGroupSetChild(uiGroup *g, uiControl *child) +{ + if (g->child != NULL) { + uiControlSetParent(g->child, NULL); + uiWindowsControlSetParentHWND(uiWindowsControl(g->child), NULL); + } + g->child = child; + if (g->child != NULL) { + uiControlSetParent(g->child, uiControl(g)); + uiWindowsControlSetParentHWND(uiWindowsControl(g->child), g->hwnd); + uiWindowsControlAssignSoleControlIDZOrder(uiWindowsControl(g->child)); + uiWindowsControlMinimumSizeChanged(uiWindowsControl(g)); + } +} + +int uiGroupMargined(uiGroup *g) +{ + return g->margined; +} + +void uiGroupSetMargined(uiGroup *g, int margined) +{ + g->margined = margined; + uiWindowsControlMinimumSizeChanged(uiWindowsControl(g)); +} + +static LRESULT CALLBACK groupSubProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData) +{ + uiGroup *g = uiGroup(dwRefData); + WINDOWPOS *wp = (WINDOWPOS *) lParam; + MINMAXINFO *mmi = (MINMAXINFO *) lParam; + int minwid, minht; + LRESULT lResult; + + if (handleParentMessages(hwnd, uMsg, wParam, lParam, &lResult) != FALSE) + return lResult; + switch (uMsg) { + case WM_WINDOWPOSCHANGED: + if ((wp->flags & SWP_NOSIZE) != 0) + break; + groupRelayout(g); + return 0; + case WM_GETMINMAXINFO: + lResult = DefWindowProcW(hwnd, uMsg, wParam, lParam); + uiWindowsControlMinimumSize(uiWindowsControl(g), &minwid, &minht); + mmi->ptMinTrackSize.x = minwid; + mmi->ptMinTrackSize.y = minht; + return lResult; + case WM_NCDESTROY: + if (RemoveWindowSubclass(hwnd, groupSubProc, uIdSubclass) == FALSE) + logLastError(L"error removing groupbox subclass"); + break; + } + return DefSubclassProc(hwnd, uMsg, wParam, lParam); +} + +uiGroup *uiNewGroup(const char *text) +{ + uiGroup *g; + WCHAR *wtext; + + uiWindowsNewControl(uiGroup, g); + + wtext = toUTF16(text); + g->hwnd = uiWindowsEnsureCreateControlHWND(WS_EX_CONTROLPARENT, + L"button", wtext, + BS_GROUPBOX, + hInstance, NULL, + TRUE); + uiprivFree(wtext); + + if (SetWindowSubclass(g->hwnd, groupSubProc, 0, (DWORD_PTR) g) == FALSE) + logLastError(L"error subclassing groupbox to handle parent messages"); + + return g; +} diff --git a/dep/libui/windows/image.cpp b/dep/libui/windows/image.cpp new file mode 100644 index 0000000..7d1a06e --- /dev/null +++ b/dep/libui/windows/image.cpp @@ -0,0 +1,281 @@ +#include "uipriv_windows.hpp" + +// TODO: +// - is the alpha channel ignored when drawing images in tables? + +IWICImagingFactory *uiprivWICFactory = NULL; + +HRESULT uiprivInitImage(void) +{ + return CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, + IID_IWICImagingFactory, (void **) (&uiprivWICFactory)); +} + +void uiprivUninitImage(void) +{ + uiprivWICFactory->Release(); + uiprivWICFactory = NULL; +} + +struct uiImage { + double width; + double height; + std::vector *bitmaps; +}; + +uiImage *uiNewImage(double width, double height) +{ + uiImage *i; + + i = uiprivNew(uiImage); + i->width = width; + i->height = height; + i->bitmaps = new std::vector; + return i; +} + +void uiFreeImage(uiImage *i) +{ + for (IWICBitmap *b : *(i->bitmaps)) + b->Release(); + delete i->bitmaps; + uiprivFree(i); +} + +// to make things easier, we store images in WIC in the same way we store them in GDI (as system-endian ARGB) and premultiplied (as that's what AlphaBlend() expects (TODO confirm this)) +// but what WIC format is system-endian ARGB? for a little-endian system, that's BGRA +// it turns out that the Windows 8 BMP encoder uses BGRA if told to (https://docs.microsoft.com/en-us/windows/desktop/wic/bmp-format-overview) +// it also turns out Direct2D requires PBGRA for drawing (https://docs.microsoft.com/en-us/windows/desktop/wic/-wic-bitmapsources-howto-drawusingd2d) +// so I guess we can assume PBGRA is correct...? (TODO) +#define formatForGDI GUID_WICPixelFormat32bppPBGRA + +void uiImageAppend(uiImage *i, void *pixels, int pixelWidth, int pixelHeight, int byteStride) +{ + IWICBitmap *b; + WICRect r; + IWICBitmapLock *l; + uint8_t *pix, *data; + // TODO WICInProcPointer is not available in MinGW-w64 + BYTE *dipp; + UINT size; + UINT realStride; + int x, y; + HRESULT hr; + + hr = uiprivWICFactory->CreateBitmap(pixelWidth, pixelHeight, + formatForGDI, WICBitmapCacheOnDemand, + &b); + if (hr != S_OK) + logHRESULT(L"error calling CreateBitmap() in uiImageAppend()", hr); + r.X = 0; + r.Y = 0; + r.Width = pixelWidth; + r.Height = pixelHeight; + hr = b->Lock(&r, WICBitmapLockWrite, &l); + if (hr != S_OK) + logHRESULT(L"error calling Lock() in uiImageAppend()", hr); + + pix = (uint8_t *) pixels; + // TODO can size be NULL? + hr = l->GetDataPointer(&size, &dipp); + if (hr != S_OK) + logHRESULT(L"error calling GetDataPointer() in uiImageAppend()", hr); + data = (uint8_t *) dipp; + hr = l->GetStride(&realStride); + if (hr != S_OK) + logHRESULT(L"error calling GetStride() in uiImageAppend()", hr); + for (y = 0; y < pixelHeight; y++) { + for (x = 0; x < pixelWidth * 4; x += 4) { + union { + uint32_t v32; + uint8_t v8[4]; + } v; + + v.v32 = ((uint32_t) (pix[x + 3])) << 24; + v.v32 |= ((uint32_t) (pix[x])) << 16; + v.v32 |= ((uint32_t) (pix[x + 1])) << 8; + v.v32 |= ((uint32_t) (pix[x + 2])); + data[x] = v.v8[0]; + data[x + 1] = v.v8[1]; + data[x + 2] = v.v8[2]; + data[x + 3] = v.v8[3]; + } + pix += byteStride; + data += realStride; + } + + l->Release(); + i->bitmaps->push_back(b); +} + +struct matcher { + IWICBitmap *best; + int distX; + int distY; + int targetX; + int targetY; + bool foundLarger; +}; + +// TODO is this the right algorithm? +static void match(IWICBitmap *b, struct matcher *m) +{ + UINT ux, uy; + int x, y; + int x2, y2; + HRESULT hr; + + hr = b->GetSize(&ux, &uy); + if (hr != S_OK) + logHRESULT(L"error calling GetSize() in match()", hr); + x = ux; + y = uy; + if (m->best == NULL) + goto writeMatch; + + if (x < m->targetX && y < m->targetY) + if (m->foundLarger) + // always prefer larger ones + return; + if (x >= m->targetX && y >= m->targetY && !m->foundLarger) + // we set foundLarger below + goto writeMatch; + +// TODO +#define abs(x) ((x) < 0 ? -(x) : (x)) + x2 = abs(m->targetX - x); + y2 = abs(m->targetY - y); + if (x2 < m->distX && y2 < m->distY) + goto writeMatch; + + // TODO weight one dimension? threshhold? + return; + +writeMatch: + // must set this here too; otherwise the first image will never have ths set + if (x >= m->targetX && y >= m->targetY && !m->foundLarger) + m->foundLarger = true; + m->best = b; + m->distX = abs(m->targetX - x); + m->distY = abs(m->targetY - y); +} + +IWICBitmap *uiprivImageAppropriateForDC(uiImage *i, HDC dc) +{ + struct matcher m; + + m.best = NULL; + m.distX = INT_MAX; + m.distY = INT_MAX; + // TODO explain this + m.targetX = MulDiv(i->width, GetDeviceCaps(dc, LOGPIXELSX), 96); + m.targetY = MulDiv(i->height, GetDeviceCaps(dc, LOGPIXELSY), 96); + m.foundLarger = false; + for (IWICBitmap *b : *(i->bitmaps)) + match(b, &m); + return m.best; +} + +// TODO this needs to center images if the given size is not the same aspect ratio +HRESULT uiprivWICToGDI(IWICBitmap *b, HDC dc, int width, int height, HBITMAP *hb) +{ + UINT ux, uy; + int x, y; + IWICBitmapSource *src; + BITMAPINFO bmi; + VOID *bits; + BITMAP bmp; + HRESULT hr; + + hr = b->GetSize(&ux, &uy); + if (hr != S_OK) + return hr; + x = ux; + y = uy; + if (width == 0) + width = x; + if (height == 0) + height = y; + + // special case: don't invoke a scaler if the size is the same + if (width == x && height == y) { + b->AddRef(); // for the Release() later + src = b; + } else { + IWICBitmapScaler *scaler; + WICPixelFormatGUID guid; + IWICFormatConverter *conv; + + hr = uiprivWICFactory->CreateBitmapScaler(&scaler); + if (hr != S_OK) + return hr; + hr = scaler->Initialize(b, width, height, + // according to https://stackoverflow.com/questions/4250738/is-stretchblt-halftone-bilinear-for-all-scaling, this is what StretchBlt(COLORONCOLOR) does (with COLORONCOLOR being what's supported by AlphaBlend()) + WICBitmapInterpolationModeNearestNeighbor); + if (hr != S_OK) { + scaler->Release(); + return hr; + } + + // But we are not done yet! IWICBitmapScaler can use an + // entirely different pixel format than what we gave it, + // and by extension, what GDI wants. See also: + // - https://stackoverflow.com/questions/28323228/iwicbitmapscaler-doesnt-work-for-96bpprgbfloat-format + // - https://github.com/Microsoft/DirectXTex/blob/0d94e9469bc3e6080a71145f35efa559f8f2e522/DirectXTex/DirectXTexResize.cpp#L83 + hr = scaler->GetPixelFormat(&guid); + if (hr != S_OK) { + scaler->Release(); + return hr; + } + if (IsEqualGUID(guid, formatForGDI)) + src = scaler; + else { + hr = uiprivWICFactory->CreateFormatConverter(&conv); + if (hr != S_OK) { + scaler->Release(); + return hr; + } + hr = conv->Initialize(scaler, formatForGDI, + // TODO is the dither type correct in all cases? + WICBitmapDitherTypeNone, NULL, 0, WICBitmapPaletteTypeMedianCut); + scaler->Release(); + if (hr != S_OK) { + conv->Release(); + return hr; + } + src = conv; + } + } + + ZeroMemory(&bmi, sizeof (BITMAPINFO)); + bmi.bmiHeader.biSize = sizeof (BITMAPINFOHEADER); + bmi.bmiHeader.biWidth = width; + bmi.bmiHeader.biHeight = -((int) height); + bmi.bmiHeader.biPlanes = 1; + bmi.bmiHeader.biBitCount = 32; + bmi.bmiHeader.biCompression = BI_RGB; + *hb = CreateDIBSection(dc, &bmi, DIB_RGB_COLORS, + &bits, NULL, 0); + if (*hb == NULL) { + logLastError(L"CreateDIBSection()"); + hr = E_FAIL; + goto fail; + } + + // now we need to figure out the stride of the image data GDI gave us + // TODO find out if CreateDIBSection() fills that in bmi for us + // TODO fill in the error returns here too + if (GetObject(*hb, sizeof (BITMAP), &bmp) == 0) + logLastError(L"error calling GetObject() in uiprivWICToGDI()"); + hr = src->CopyPixels(NULL, bmp.bmWidthBytes, + bmp.bmWidthBytes * bmp.bmHeight, (BYTE *) bits); + +fail: + if (*hb != NULL && hr != S_OK) { + // don't bother with the error returned here + DeleteObject(*hb); + *hb = NULL; + } + src->Release(); + return hr; +} diff --git a/dep/libui/windows/init.cpp b/dep/libui/windows/init.cpp new file mode 100644 index 0000000..021ebaa --- /dev/null +++ b/dep/libui/windows/init.cpp @@ -0,0 +1,174 @@ +// 6 april 2015 +#include "uipriv_windows.hpp" +#include "attrstr.hpp" + +HINSTANCE hInstance; +int nCmdShow; + +HFONT hMessageFont; + +// LONGTERM needed? +HBRUSH hollowBrush; + +// the returned pointer is actually to the second character +// if the first character is - then free, otherwise don't +static const char *initerr(const char *message, const WCHAR *label, DWORD value) +{ + WCHAR *sysmsg; + BOOL hassysmsg; + WCHAR *wmessage; + WCHAR *wout; + char *out; + + hassysmsg = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, value, 0, (LPWSTR) (&sysmsg), 0, NULL) != 0; + if (!hassysmsg) + sysmsg = (WCHAR *) L""; // TODO + wmessage = toUTF16(message + 1); + wout = strf(L"-error initializing libui: %s; code %I32d (0x%08I32X) %s", + wmessage, + value, value, + sysmsg); + uiprivFree(wmessage); + if (hassysmsg) + LocalFree(sysmsg); // ignore error + out = toUTF8(wout); + uiprivFree(wout); + return out + 1; +} + +#define ieLastErr(msg) initerr("=" msg, L"GetLastError() ==", GetLastError()) +#define ieHRESULT(msg, hr) initerr("=" msg, L"HRESULT", (DWORD) hr) + +// LONGTERM put this declaration in a common file +uiInitOptions uiprivOptions; + +#define wantedICCClasses ( \ + ICC_STANDARD_CLASSES | /* user32.dll controls */ \ + ICC_PROGRESS_CLASS | /* progress bars */ \ + ICC_TAB_CLASSES | /* tabs */ \ + ICC_LISTVIEW_CLASSES | /* table headers */ \ + ICC_UPDOWN_CLASS | /* spinboxes */ \ + ICC_BAR_CLASSES | /* trackbar */ \ + ICC_DATE_CLASSES | /* date/time picker */ \ + 0) + +const char *uiInit(uiInitOptions *o) +{ + STARTUPINFOW si; + const char *ce; + HICON hDefaultIcon; + HCURSOR hDefaultCursor; + NONCLIENTMETRICSW ncm; + INITCOMMONCONTROLSEX icc; + HRESULT hr; + + uiprivOptions = *o; + + initAlloc(); + + nCmdShow = SW_SHOWDEFAULT; + GetStartupInfoW(&si); + if ((si.dwFlags & STARTF_USESHOWWINDOW) != 0) + nCmdShow = si.wShowWindow; + + // LONGTERM set DPI awareness + + hDefaultIcon = LoadIconW(NULL, IDI_APPLICATION); + if (hDefaultIcon == NULL) + return ieLastErr("loading default icon for window classes"); + hDefaultCursor = LoadCursorW(NULL, IDC_ARROW); + if (hDefaultCursor == NULL) + return ieLastErr("loading default cursor for window classes"); + + ce = initUtilWindow(hDefaultIcon, hDefaultCursor); + if (ce != NULL) + return initerr(ce, L"GetLastError() ==", GetLastError()); + + if (registerWindowClass(hDefaultIcon, hDefaultCursor) == 0) + return ieLastErr("registering uiWindow window class"); + + ZeroMemory(&ncm, sizeof (NONCLIENTMETRICSW)); + ncm.cbSize = sizeof (NONCLIENTMETRICSW); + if (SystemParametersInfoW(SPI_GETNONCLIENTMETRICS, sizeof (NONCLIENTMETRICSW), &ncm, sizeof (NONCLIENTMETRICSW)) == 0) + return ieLastErr("getting default fonts"); + hMessageFont = CreateFontIndirectW(&(ncm.lfMessageFont)); + if (hMessageFont == NULL) + return ieLastErr("loading default messagebox font; this is the default UI font"); + + if (initContainer(hDefaultIcon, hDefaultCursor) == 0) + return ieLastErr("initializing uiWindowsMakeContainer() window class"); + + hollowBrush = (HBRUSH) GetStockObject(HOLLOW_BRUSH); + if (hollowBrush == NULL) + return ieLastErr("getting hollow brush"); + + ZeroMemory(&icc, sizeof (INITCOMMONCONTROLSEX)); + icc.dwSize = sizeof (INITCOMMONCONTROLSEX); + icc.dwICC = wantedICCClasses; + if (InitCommonControlsEx(&icc) == 0) + return ieLastErr("initializing Common Controls"); + + hr = CoInitialize(NULL); + if (hr != S_OK && hr != S_FALSE) + return ieHRESULT("initializing COM", hr); + // LONGTERM initialize COM security + // LONGTERM (windows vista) turn off COM exception handling + + hr = initDraw(); + if (hr != S_OK) + return ieHRESULT("initializing Direct2D", hr); + + hr = uiprivInitDrawText(); + if (hr != S_OK) + return ieHRESULT("initializing DirectWrite", hr); + + if (registerAreaClass(hDefaultIcon, hDefaultCursor) == 0) + return ieLastErr("registering uiArea window class"); + + if (registerMessageFilter() == 0) + return ieLastErr("registering libui message filter"); + + if (registerD2DScratchClass(hDefaultIcon, hDefaultCursor) == 0) + return ieLastErr("initializing D2D scratch window class"); + + hr = uiprivInitImage(); + if (hr != S_OK) + return ieHRESULT("initializing WIC", hr); + + return NULL; +} + +void uiUninit(void) +{ + uiprivUninitTimers(); + uiprivUninitImage(); + uninitMenus(); + unregisterD2DScratchClass(); + unregisterMessageFilter(); + unregisterArea(); + uiprivUninitDrawText(); + uninitDraw(); + CoUninitialize(); + if (DeleteObject(hollowBrush) == 0) + logLastError(L"error freeing hollow brush"); + uninitContainer(); + if (DeleteObject(hMessageFont) == 0) + logLastError(L"error deleting control font"); + unregisterWindowClass(); + // no need to delete the default icon or cursor; see http://stackoverflow.com/questions/30603077/ + uninitUtilWindow(); + uninitAlloc(); +} + +void uiFreeInitError(const char *err) +{ + if (*(err - 1) == '-') + uiprivFree((void *) (err - 1)); +} + +BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) +{ + if (fdwReason == DLL_PROCESS_ATTACH) + hInstance = hinstDLL; + return TRUE; +} diff --git a/dep/libui/windows/label.cpp b/dep/libui/windows/label.cpp new file mode 100644 index 0000000..94a0d88 --- /dev/null +++ b/dep/libui/windows/label.cpp @@ -0,0 +1,57 @@ +// 11 april 2015 +#include "uipriv_windows.hpp" + +struct uiLabel { + uiWindowsControl c; + HWND hwnd; +}; + +uiWindowsControlAllDefaults(uiLabel) + +// via http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing +#define labelHeight 8 + +static void uiLabelMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + uiLabel *l = uiLabel(c); + uiWindowsSizing sizing; + int y; + + *width = uiWindowsWindowTextWidth(l->hwnd); + y = labelHeight; + uiWindowsGetSizing(l->hwnd, &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, NULL, &y); + *height = y; +} + +char *uiLabelText(uiLabel *l) +{ + return uiWindowsWindowText(l->hwnd); +} + +void uiLabelSetText(uiLabel *l, const char *text) +{ + uiWindowsSetWindowText(l->hwnd, text); + // changing the text might necessitate a change in the label's size + uiWindowsControlMinimumSizeChanged(uiWindowsControl(l)); +} + +uiLabel *uiNewLabel(const char *text) +{ + uiLabel *l; + WCHAR *wtext; + + uiWindowsNewControl(uiLabel, l); + + wtext = toUTF16(text); + l->hwnd = uiWindowsEnsureCreateControlHWND(0, + L"static", wtext, + // SS_LEFTNOWORDWRAP clips text past the end; SS_NOPREFIX avoids accelerator translation + // controls are vertically aligned to the top by default (thanks Xeek in irc.freenode.net/#winapi) + SS_LEFTNOWORDWRAP | SS_NOPREFIX, + hInstance, NULL, + TRUE); + uiprivFree(wtext); + + return l; +} diff --git a/dep/libui/windows/libui.manifest b/dep/libui/windows/libui.manifest new file mode 100644 index 0000000..8beb6cf --- /dev/null +++ b/dep/libui/windows/libui.manifest @@ -0,0 +1,31 @@ + + + +Your application description here. + + + + + + + + + + + + + + + diff --git a/dep/libui/windows/main.cpp b/dep/libui/windows/main.cpp new file mode 100644 index 0000000..004e784 --- /dev/null +++ b/dep/libui/windows/main.cpp @@ -0,0 +1,160 @@ +// 6 april 2015 +#include "uipriv_windows.hpp" + +static HHOOK filter; + +static LRESULT CALLBACK filterProc(int code, WPARAM wParam, LPARAM lParam) +{ + MSG *msg = (MSG *) lParam; + + if (code < 0) + goto callNext; + + if (areaFilter(msg)) // don't continue to our IsDialogMessage() hack if the area handled it + goto discard; + + // TODO IsDialogMessage() hack here + + // otherwise keep going + goto callNext; + +discard: + // we handled it; discard the message so the dialog manager doesn't see it + return 1; + +callNext: + return CallNextHookEx(filter, code, wParam, lParam); +} + +int registerMessageFilter(void) +{ + filter = SetWindowsHookExW(WH_MSGFILTER, + filterProc, + hInstance, + GetCurrentThreadId()); + return filter != NULL; +} + +void unregisterMessageFilter(void) +{ + if (UnhookWindowsHookEx(filter) == 0) + logLastError(L"error unregistering libui message filter"); +} + +// LONGTERM http://blogs.msdn.com/b/oldnewthing/archive/2005/04/08/406509.aspx when adding accelerators, TranslateAccelerators() before IsDialogMessage() + +static void processMessage(MSG *msg) +{ + HWND correctParent; + + if (msg->hwnd != NULL) + correctParent = parentToplevel(msg->hwnd); + else // just to be safe + correctParent = GetActiveWindow(); + if (correctParent != NULL) + // this calls our mesage filter above for us + if (IsDialogMessage(correctParent, msg) != 0) + return; + TranslateMessage(msg); + DispatchMessageW(msg); +} + +static int waitMessage(MSG *msg) +{ + int res; + + res = GetMessageW(msg, NULL, 0, 0); + if (res < 0) { + logLastError(L"error calling GetMessage()"); + return 0; // bail out on error + } + return res != 0; // returns false on WM_QUIT +} + +void uiMain(void) +{ + while (uiMainStep(1)) + ; +} + +void uiMainSteps(void) +{ + // don't need to do anything here +} + +static int peekMessage(MSG *msg) +{ + BOOL res; + + res = PeekMessageW(msg, NULL, 0, 0, PM_REMOVE); + if (res == 0) + return 2; // no message available + if (msg->message != WM_QUIT) + return 1; // a message + return 0; // WM_QUIT +} + +int uiMainStep(int wait) +{ + MSG msg; + + if (wait) { + if (!waitMessage(&msg)) + return 0; + processMessage(&msg); + return 1; + } + + // don't wait for a message + switch (peekMessage(&msg)) { + case 0: // quit + // TODO PostQuitMessage() again? + return 0; + case 1: // process a message + processMessage(&msg); + // fall out to the case for no message + } + return 1; // no message +} + +void uiQuit(void) +{ + PostQuitMessage(0); +} + +void uiQueueMain(void (*f)(void *data), void *data) +{ + if (PostMessageW(utilWindow, msgQueued, (WPARAM) f, (LPARAM) data) == 0) + // LONGTERM this is likely not safe to call across threads (allocates memory) + logLastError(L"error queueing function to run on main thread"); +} + +static std::map timers; + +void uiTimer(int milliseconds, int (*f)(void *data), void *data) +{ + uiprivTimer *timer; + + timer = uiprivNew(uiprivTimer); + timer->f = f; + timer->data = data; + // note that timer IDs are pointer sized precisely so we can use them as timer IDs; see https://blogs.msdn.microsoft.com/oldnewthing/20150924-00/?p=91521 + if (SetTimer(utilWindow, (UINT_PTR) timer, milliseconds, NULL) == 0) + logLastError(L"error calling SetTimer() in uiTimer()"); + timers[timer] = true; +} + +void uiprivFreeTimer(uiprivTimer *t) +{ + timers.erase(t); + uiprivFree(t); +} + +// since timers use uiprivAlloc(), we have to clean them up in uiUninit(), or else we'll get dangling allocation errors +void uiprivUninitTimers(void) +{ + // TODO why doesn't auto t : timers work? + for (auto t = timers.begin(); t != timers.end(); t++) + uiprivFree(t->first); + timers.clear(); +} diff --git a/dep/libui/windows/menu.cpp b/dep/libui/windows/menu.cpp new file mode 100644 index 0000000..65791bf --- /dev/null +++ b/dep/libui/windows/menu.cpp @@ -0,0 +1,369 @@ +// 24 april 2015 +#include "uipriv_windows.hpp" + +// LONGTERM migrate to std::vector + +static uiMenu **menus = NULL; +static size_t len = 0; +static size_t cap = 0; +static BOOL menusFinalized = FALSE; +static WORD curID = 100; // start somewhere safe +static BOOL hasQuit = FALSE; +static BOOL hasPreferences = FALSE; +static BOOL hasAbout = FALSE; + +struct uiMenu { + WCHAR *name; + uiMenuItem **items; + size_t len; + size_t cap; +}; + +struct uiMenuItem { + WCHAR *name; + int type; + WORD id; + void (*onClicked)(uiMenuItem *, uiWindow *, void *); + void *onClickedData; + BOOL disabled; // template for new instances; kept in sync with everything else + BOOL checked; + HMENU *hmenus; + size_t len; + size_t cap; +}; + +enum { + typeRegular, + typeCheckbox, + typeQuit, + typePreferences, + typeAbout, + typeSeparator, +}; + +#define grow 32 + +static void sync(uiMenuItem *item) +{ + size_t i; + MENUITEMINFOW mi; + + ZeroMemory(&mi, sizeof (MENUITEMINFOW)); + mi.cbSize = sizeof (MENUITEMINFOW); + mi.fMask = MIIM_STATE; + if (item->disabled) + mi.fState |= MFS_DISABLED; + if (item->checked) + mi.fState |= MFS_CHECKED; + + for (i = 0; i < item->len; i++) + if (SetMenuItemInfo(item->hmenus[i], item->id, FALSE, &mi) == 0) + logLastError(L"error synchronizing menu items"); +} + +static void defaultOnClicked(uiMenuItem *item, uiWindow *w, void *data) +{ + // do nothing +} + +static void onQuitClicked(uiMenuItem *item, uiWindow *w, void *data) +{ + if (uiprivShouldQuit()) + uiQuit(); +} + +void uiMenuItemEnable(uiMenuItem *i) +{ + i->disabled = FALSE; + sync(i); +} + +void uiMenuItemDisable(uiMenuItem *i) +{ + i->disabled = TRUE; + sync(i); +} + +void uiMenuItemOnClicked(uiMenuItem *i, void (*f)(uiMenuItem *, uiWindow *, void *), void *data) +{ + if (i->type == typeQuit) + uiprivUserBug("You can not call uiMenuItemOnClicked() on a Quit item; use uiOnShouldQuit() instead."); + i->onClicked = f; + i->onClickedData = data; +} + +int uiMenuItemChecked(uiMenuItem *i) +{ + return i->checked != FALSE; +} + +void uiMenuItemSetChecked(uiMenuItem *i, int checked) +{ + // use explicit values + i->checked = FALSE; + if (checked) + i->checked = TRUE; + sync(i); +} + +static uiMenuItem *newItem(uiMenu *m, int type, const char *name) +{ + uiMenuItem *item; + + if (menusFinalized) + uiprivUserBug("You can not create a new menu item after menus have been finalized."); + + if (m->len >= m->cap) { + m->cap += grow; + m->items = (uiMenuItem **) uiprivRealloc(m->items, m->cap * sizeof (uiMenuItem *), "uiMenuitem *[]"); + } + + item = uiprivNew(uiMenuItem); + + m->items[m->len] = item; + m->len++; + + item->type = type; + switch (item->type) { + case typeQuit: + item->name = toUTF16("Quit"); + break; + case typePreferences: + item->name = toUTF16("Preferences..."); + break; + case typeAbout: + item->name = toUTF16("About"); + break; + case typeSeparator: + break; + default: + item->name = toUTF16(name); + break; + } + + if (item->type != typeSeparator) { + item->id = curID; + curID++; + } + + if (item->type == typeQuit) { + // can't call uiMenuItemOnClicked() here + item->onClicked = onQuitClicked; + item->onClickedData = NULL; + } else + uiMenuItemOnClicked(item, defaultOnClicked, NULL); + + return item; +} + +uiMenuItem *uiMenuAppendItem(uiMenu *m, const char *name) +{ + return newItem(m, typeRegular, name); +} + +uiMenuItem *uiMenuAppendCheckItem(uiMenu *m, const char *name) +{ + return newItem(m, typeCheckbox, name); +} + +uiMenuItem *uiMenuAppendQuitItem(uiMenu *m) +{ + if (hasQuit) + uiprivUserBug("You can not have multiple Quit menu items in a program."); + hasQuit = TRUE; + newItem(m, typeSeparator, NULL); + return newItem(m, typeQuit, NULL); +} + +uiMenuItem *uiMenuAppendPreferencesItem(uiMenu *m) +{ + if (hasPreferences) + uiprivUserBug("You can not have multiple Preferences menu items in a program."); + hasPreferences = TRUE; + newItem(m, typeSeparator, NULL); + return newItem(m, typePreferences, NULL); +} + +uiMenuItem *uiMenuAppendAboutItem(uiMenu *m) +{ + if (hasAbout) + // TODO place these uiprivImplBug() and uiprivUserBug() strings in a header + uiprivUserBug("You can not have multiple About menu items in a program."); + hasAbout = TRUE; + newItem(m, typeSeparator, NULL); + return newItem(m, typeAbout, NULL); +} + +void uiMenuAppendSeparator(uiMenu *m) +{ + newItem(m, typeSeparator, NULL); +} + +uiMenu *uiNewMenu(const char *name) +{ + uiMenu *m; + + if (menusFinalized) + uiprivUserBug("You can not create a new menu after menus have been finalized."); + if (len >= cap) { + cap += grow; + menus = (uiMenu **) uiprivRealloc(menus, cap * sizeof (uiMenu *), "uiMenu *[]"); + } + + m = uiprivNew(uiMenu); + + menus[len] = m; + len++; + + m->name = toUTF16(name); + + return m; +} + +static void appendMenuItem(HMENU menu, uiMenuItem *item) +{ + UINT uFlags; + + uFlags = MF_SEPARATOR; + if (item->type != typeSeparator) { + uFlags = MF_STRING; + if (item->disabled) + uFlags |= MF_DISABLED | MF_GRAYED; + if (item->checked) + uFlags |= MF_CHECKED; + } + if (AppendMenuW(menu, uFlags, item->id, item->name) == 0) + logLastError(L"error appending menu item"); + + if (item->len >= item->cap) { + item->cap += grow; + item->hmenus = (HMENU *) uiprivRealloc(item->hmenus, item->cap * sizeof (HMENU), "HMENU[]"); + } + item->hmenus[item->len] = menu; + item->len++; +} + +static HMENU makeMenu(uiMenu *m) +{ + HMENU menu; + size_t i; + + menu = CreatePopupMenu(); + if (menu == NULL) + logLastError(L"error creating menu"); + for (i = 0; i < m->len; i++) + appendMenuItem(menu, m->items[i]); + return menu; +} + +HMENU makeMenubar(void) +{ + HMENU menubar; + HMENU menu; + size_t i; + + menusFinalized = TRUE; + + menubar = CreateMenu(); + if (menubar == NULL) + logLastError(L"error creating menubar"); + + for (i = 0; i < len; i++) { + menu = makeMenu(menus[i]); + if (AppendMenuW(menubar, MF_POPUP | MF_STRING, (UINT_PTR) menu, menus[i]->name) == 0) + logLastError(L"error appending menu to menubar"); + } + + return menubar; +} + +void runMenuEvent(WORD id, uiWindow *w) +{ + uiMenu *m; + uiMenuItem *item; + size_t i, j; + + // this isn't optimal, but it works, and it should be just fine for most cases + for (i = 0; i < len; i++) { + m = menus[i]; + for (j = 0; j < m->len; j++) { + item = m->items[j]; + if (item->id == id) + goto found; + } + } + // no match + uiprivImplBug("unknown menu ID %hu in runMenuEvent()", id); + +found: + // first toggle checkboxes, if any + if (item->type == typeCheckbox) + uiMenuItemSetChecked(item, !uiMenuItemChecked(item)); + + // then run the event + (*(item->onClicked))(item, w, item->onClickedData); +} + +static void freeMenu(uiMenu *m, HMENU submenu) +{ + size_t i; + uiMenuItem *item; + size_t j; + + for (i = 0; i < m->len; i++) { + item = m->items[i]; + for (j = 0; j < item->len; j++) + if (item->hmenus[j] == submenu) + break; + if (j >= item->len) + uiprivImplBug("submenu handle %p not found in freeMenu()", submenu); + for (; j < item->len - 1; j++) + item->hmenus[j] = item->hmenus[j + 1]; + item->hmenus[j] = NULL; + item->len--; + } +} + +void freeMenubar(HMENU menubar) +{ + size_t i; + MENUITEMINFOW mi; + + for (i = 0; i < len; i++) { + ZeroMemory(&mi, sizeof (MENUITEMINFOW)); + mi.cbSize = sizeof (MENUITEMINFOW); + mi.fMask = MIIM_SUBMENU; + if (GetMenuItemInfoW(menubar, i, TRUE, &mi) == 0) + logLastError(L"error getting menu to delete item references from"); + freeMenu(menus[i], mi.hSubMenu); + } + // no need to worry about destroying any menus; destruction of the window they're in will do it for us +} + +void uninitMenus(void) +{ + uiMenu *m; + uiMenuItem *item; + size_t i, j; + + for (i = 0; i < len; i++) { + m = menus[i]; + uiprivFree(m->name); + for (j = 0; j < m->len; j++) { + item = m->items[j]; + if (item->len != 0) + // LONGTERM uiprivUserBug()? + uiprivImplBug("menu item %p (%ws) still has uiWindows attached; did you forget to destroy some windows?", item, item->name); + if (item->name != NULL) + uiprivFree(item->name); + if (item->hmenus != NULL) + uiprivFree(item->hmenus); + uiprivFree(item); + } + if (m->items != NULL) + uiprivFree(m->items); + uiprivFree(m); + } + if (menus != NULL) + uiprivFree(menus); +} diff --git a/dep/libui/windows/meson.build b/dep/libui/windows/meson.build new file mode 100644 index 0000000..80c7bd8 --- /dev/null +++ b/dep/libui/windows/meson.build @@ -0,0 +1,91 @@ +# 23 march 2019 + +windows = import('windows') + +libui_sources += [ + 'windows/alloc.cpp', + 'windows/area.cpp', + 'windows/areadraw.cpp', + 'windows/areaevents.cpp', + 'windows/areascroll.cpp', + 'windows/areautil.cpp', + 'windows/attrstr.cpp', + 'windows/box.cpp', + 'windows/button.cpp', + 'windows/checkbox.cpp', + 'windows/colorbutton.cpp', + 'windows/colordialog.cpp', + 'windows/combobox.cpp', + 'windows/container.cpp', + 'windows/control.cpp', + 'windows/d2dscratch.cpp', + 'windows/datetimepicker.cpp', + 'windows/debug.cpp', + 'windows/draw.cpp', + 'windows/drawmatrix.cpp', + 'windows/drawpath.cpp', + 'windows/drawtext.cpp', + 'windows/dwrite.cpp', + 'windows/editablecombo.cpp', + 'windows/entry.cpp', + 'windows/events.cpp', + 'windows/fontbutton.cpp', + 'windows/fontdialog.cpp', + 'windows/fontmatch.cpp', + 'windows/form.cpp', + 'windows/graphemes.cpp', + 'windows/grid.cpp', + 'windows/group.cpp', + 'windows/image.cpp', + 'windows/init.cpp', + 'windows/label.cpp', + 'windows/main.cpp', + 'windows/menu.cpp', + 'windows/multilineentry.cpp', + 'windows/opentype.cpp', + 'windows/parent.cpp', + 'windows/progressbar.cpp', + 'windows/radiobuttons.cpp', + 'windows/separator.cpp', + 'windows/sizing.cpp', + 'windows/slider.cpp', + 'windows/spinbox.cpp', + 'windows/stddialogs.cpp', + 'windows/tab.cpp', + 'windows/table.cpp', + 'windows/tabledispinfo.cpp', + 'windows/tabledraw.cpp', + 'windows/tableediting.cpp', + 'windows/tablemetrics.cpp', + 'windows/tabpage.cpp', + 'windows/text.cpp', + 'windows/utf16.cpp', + 'windows/utilwin.cpp', + 'windows/window.cpp', + 'windows/winpublic.cpp', + 'windows/winutil.cpp', +] + +# resources.rc only contains the libui manifest. +# For a DLL, we have to include this directly, so we do so. +# Windows won't link resources in static libraries, so including this would have no effect. +# In those cases, we just need them to include the manifest with the executable (or link it directly into the output executable themselves); they can also customize the manifest as they see fit (assuming nothing breaks in the process). +if libui_mode == 'shared' + libui_sources += [ + windows.compile_resources('resources.rc', + args: libui_manifest_args, + depend_files: ['libui.manifest']), + ] +endif + +# TODO prune this list +foreach lib : ['user32', 'kernel32', 'gdi32', 'comctl32', 'uxtheme', 'msimg32', 'comdlg32', 'd2d1', 'dwrite', 'ole32', 'oleaut32', 'oleacc', 'uuid', 'windowscodecs'] + libui_deps += [ + meson.get_compiler('cpp').find_library(lib, + required: true), + ] +endforeach + +if libui_OS == 'windows' and libui_mode == 'shared' and not libui_MSVC + error('Sorry, but libui for Windows can currently only be built as a static library with MinGW. You will need to either build as a static library or switch to MSVC.') +endif diff --git a/dep/libui/windows/multilineentry.cpp b/dep/libui/windows/multilineentry.cpp new file mode 100644 index 0000000..1365e4e --- /dev/null +++ b/dep/libui/windows/multilineentry.cpp @@ -0,0 +1,152 @@ +// 8 april 2015 +#include "uipriv_windows.hpp" + +// TODO there's alpha darkening of text going on in read-only ones; something is up in our parent logic + +struct uiMultilineEntry { + uiWindowsControl c; + HWND hwnd; + void (*onChanged)(uiMultilineEntry *, void *); + void *onChangedData; + BOOL inhibitChanged; +}; + +static BOOL onWM_COMMAND(uiControl *c, HWND hwnd, WORD code, LRESULT *lResult) +{ + uiMultilineEntry *e = uiMultilineEntry(c); + + if (code != EN_CHANGE) + return FALSE; + if (e->inhibitChanged) + return FALSE; + (*(e->onChanged))(e, e->onChangedData); + *lResult = 0; + return TRUE; +} + +static void uiMultilineEntryDestroy(uiControl *c) +{ + uiMultilineEntry *e = uiMultilineEntry(c); + + uiWindowsUnregisterWM_COMMANDHandler(e->hwnd); + uiWindowsEnsureDestroyWindow(e->hwnd); + uiFreeControl(uiControl(e)); +} + +uiWindowsControlAllDefaultsExceptDestroy(uiMultilineEntry) + +// from http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing +#define entryWidth 107 /* this is actually the shorter progress bar width, but Microsoft only indicates as wide as necessary */ +// LONGTERM change this for multiline text boxes (longterm because how?) +#define entryHeight 14 + +static void uiMultilineEntryMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + uiMultilineEntry *e = uiMultilineEntry(c); + uiWindowsSizing sizing; + int x, y; + + x = entryWidth; + y = entryHeight; + uiWindowsGetSizing(e->hwnd, &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, &x, &y); + *width = x; + *height = y; +} + +static void defaultOnChanged(uiMultilineEntry *e, void *data) +{ + // do nothing +} + +char *uiMultilineEntryText(uiMultilineEntry *e) +{ + char *out; + + out = uiWindowsWindowText(e->hwnd); + CRLFtoLF(out); + return out; +} + +void uiMultilineEntrySetText(uiMultilineEntry *e, const char *text) +{ + char *crlf; + + // doing this raises an EN_CHANGED + e->inhibitChanged = TRUE; + crlf = LFtoCRLF(text); + uiWindowsSetWindowText(e->hwnd, crlf); + uiprivFree(crlf); + e->inhibitChanged = FALSE; + // don't queue the control for resize; entry sizes are independent of their contents +} + +void uiMultilineEntryAppend(uiMultilineEntry *e, const char *text) +{ + LRESULT n; + char *crlf; + WCHAR *wtext; + + // doing this raises an EN_CHANGED + e->inhibitChanged = TRUE; + // TODO preserve selection? caret? what if caret used to be at end? + // TODO scroll to bottom? + n = SendMessageW(e->hwnd, WM_GETTEXTLENGTH, 0, 0); + SendMessageW(e->hwnd, EM_SETSEL, n, n); + crlf = LFtoCRLF(text); + wtext = toUTF16(crlf); + uiprivFree(crlf); + SendMessageW(e->hwnd, EM_REPLACESEL, FALSE, (LPARAM) wtext); + uiprivFree(wtext); + e->inhibitChanged = FALSE; +} + +void uiMultilineEntryOnChanged(uiMultilineEntry *e, void (*f)(uiMultilineEntry *, void *), void *data) +{ + e->onChanged = f; + e->onChangedData = data; +} + +int uiMultilineEntryReadOnly(uiMultilineEntry *e) +{ + return (getStyle(e->hwnd) & ES_READONLY) != 0; +} + +void uiMultilineEntrySetReadOnly(uiMultilineEntry *e, int readonly) +{ + WPARAM ro; + + ro = (WPARAM) FALSE; + if (readonly) + ro = (WPARAM) TRUE; + if (SendMessage(e->hwnd, EM_SETREADONLY, ro, 0) == 0) + logLastError(L"error making uiMultilineEntry read-only"); +} + +static uiMultilineEntry *finishMultilineEntry(DWORD style) +{ + uiMultilineEntry *e; + + uiWindowsNewControl(uiMultilineEntry, e); + + e->hwnd = uiWindowsEnsureCreateControlHWND(WS_EX_CLIENTEDGE, + L"edit", L"", + ES_AUTOVSCROLL | ES_LEFT | ES_MULTILINE | ES_NOHIDESEL | ES_WANTRETURN | WS_TABSTOP | WS_VSCROLL | style, + hInstance, NULL, + TRUE); + + uiWindowsRegisterWM_COMMANDHandler(e->hwnd, onWM_COMMAND, uiControl(e)); + uiMultilineEntryOnChanged(e, defaultOnChanged, NULL); + + return e; +} + +uiMultilineEntry *uiNewMultilineEntry(void) +{ + return finishMultilineEntry(0); +} + +uiMultilineEntry *uiNewNonWrappingMultilineEntry(void) +{ + return finishMultilineEntry(WS_HSCROLL | ES_AUTOHSCROLL); +} diff --git a/dep/libui/windows/notes b/dep/libui/windows/notes new file mode 100644 index 0000000..f554dd2 --- /dev/null +++ b/dep/libui/windows/notes @@ -0,0 +1,3 @@ +DIALOGS +do not accelerate OK and Cancel buttons in dialogs + http://blogs.msdn.com/b/oldnewthing/archive/2008/05/08/8467905.aspx diff --git a/dep/libui/windows/opentype.cpp b/dep/libui/windows/opentype.cpp new file mode 100644 index 0000000..777f30d --- /dev/null +++ b/dep/libui/windows/opentype.cpp @@ -0,0 +1,33 @@ +// 11 may 2017 +#include "uipriv_windows.hpp" +#include "attrstr.hpp" + +// TODO pull out my decision for empty uiOpenTypeFeatures, assuming that it isn't in another file or that I even made one + +static uiForEach addToTypography(const uiOpenTypeFeatures *otf, char a, char b, char c, char d, uint32_t value, void *data) +{ + IDWriteTypography *dt = (IDWriteTypography *) data; + DWRITE_FONT_FEATURE dff; + HRESULT hr; + + ZeroMemory(&dff, sizeof (DWRITE_FONT_FEATURE)); + // yes, the cast here is necessary (the compiler will complain otherwise)... + dff.nameTag = (DWRITE_FONT_FEATURE_TAG) DWRITE_MAKE_OPENTYPE_TAG(a, b, c, d); + dff.parameter = (UINT32) value; + hr = dt->AddFontFeature(dff); + if (hr != S_OK) + logHRESULT(L"error adding OpenType feature to IDWriteTypography", hr); + return uiForEachContinue; +} + +IDWriteTypography *uiprivOpenTypeFeaturesToIDWriteTypography(const uiOpenTypeFeatures *otf) +{ + IDWriteTypography *dt; + HRESULT hr; + + hr = dwfactory->CreateTypography(&dt); + if (hr != S_OK) + logHRESULT(L"error creating IDWriteTypography", hr); + uiOpenTypeFeaturesForEach(otf, addToTypography, dt); + return dt; +} diff --git a/dep/libui/windows/parent.cpp b/dep/libui/windows/parent.cpp new file mode 100644 index 0000000..bde6fb9 --- /dev/null +++ b/dep/libui/windows/parent.cpp @@ -0,0 +1,144 @@ +// 26 april 2015 +#include "uipriv_windows.hpp" + +// This contains code used by all uiControls that contain other controls. +// It also contains the code to draw the background of a container.c container, as that is a variant of the WM_CTLCOLORxxx handler code. + +static HBRUSH parentBrush = NULL; + +static HWND parentWithBackground(HWND hwnd) +{ + HWND parent; + int cls; + + parent = hwnd; + for (;;) { + parent = parentOf(parent); + // skip groupboxes; they're (supposed to be) transparent + // skip uiContainers; they don't draw anything + cls = windowClassOf(parent, L"button", containerClass, NULL); + if (cls != 0 && cls != 1) + break; + } + return parent; +} + +struct parentDraw { + HDC cdc; + HBITMAP bitmap; + HBITMAP prevbitmap; +}; + +static HRESULT parentDraw(HDC dc, HWND parent, struct parentDraw *pd) +{ + RECT r; + + uiWindowsEnsureGetClientRect(parent, &r); + pd->cdc = CreateCompatibleDC(dc); + if (pd->cdc == NULL) + return logLastError(L"error creating compatible DC"); + pd->bitmap = CreateCompatibleBitmap(dc, r.right - r.left, r.bottom - r.top); + if (pd->bitmap == NULL) + return logLastError(L"error creating compatible bitmap"); + pd->prevbitmap = (HBITMAP) SelectObject(pd->cdc, pd->bitmap); + if (pd->prevbitmap == NULL) + return logLastError(L"error selecting bitmap into compatible DC"); + SendMessageW(parent, WM_PRINTCLIENT, (WPARAM) (pd->cdc), PRF_CLIENT); + return S_OK; +} + +static void endParentDraw(struct parentDraw *pd) +{ + // continue in case of any error + if (pd->prevbitmap != NULL) + if (((HBITMAP) SelectObject(pd->cdc, pd->prevbitmap)) != pd->bitmap) + logLastError(L"error selecting previous bitmap back into compatible DC"); + if (pd->bitmap != NULL) + if (DeleteObject(pd->bitmap) == 0) + logLastError(L"error deleting compatible bitmap"); + if (pd->cdc != NULL) + if (DeleteDC(pd->cdc) == 0) + logLastError(L"error deleting compatible DC"); +} + +// see http://www.codeproject.com/Articles/5978/Correctly-drawn-themed-dialogs-in-WinXP +static HBRUSH getControlBackgroundBrush(HWND hwnd, HDC dc) +{ + HWND parent; + RECT hwndScreenRect; + struct parentDraw pd; + HBRUSH brush; + HRESULT hr; + + parent = parentWithBackground(hwnd); + + hr = parentDraw(dc, parent, &pd); + if (hr != S_OK) + return NULL; + brush = CreatePatternBrush(pd.bitmap); + if (brush == NULL) { + logLastError(L"error creating pattern brush"); + endParentDraw(&pd); + return NULL; + } + endParentDraw(&pd); + + // now figure out where the control is relative to the parent so we can align the brush properly + // if anything fails, give up and return the brush as-is + uiWindowsEnsureGetWindowRect(hwnd, &hwndScreenRect); + // this will be in screen coordinates; convert to parent coordinates + mapWindowRect(NULL, parent, &hwndScreenRect); + if (SetBrushOrgEx(dc, -hwndScreenRect.left, -hwndScreenRect.top, NULL) == 0) + logLastError(L"error setting brush origin"); + + return brush; +} + +void paintContainerBackground(HWND hwnd, HDC dc, RECT *paintRect) +{ + HWND parent; + RECT paintRectParent; + struct parentDraw pd; + HRESULT hr; + + parent = parentWithBackground(hwnd); + hr = parentDraw(dc, parent, &pd); + if (hr != S_OK) // we couldn't get it; draw nothing + return; + + paintRectParent = *paintRect; + mapWindowRect(hwnd, parent, &paintRectParent); + if (BitBlt(dc, paintRect->left, paintRect->top, paintRect->right - paintRect->left, paintRect->bottom - paintRect->top, + pd.cdc, paintRectParent.left, paintRectParent.top, + SRCCOPY) == 0) + logLastError(L"error drawing parent background over uiContainer"); + + endParentDraw(&pd); +} + +// TODO make this public if we want custom containers +// why have this to begin with? http://blogs.msdn.com/b/oldnewthing/archive/2010/03/16/9979112.aspx +BOOL handleParentMessages(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *lResult) +{ + switch (uMsg) { + case WM_COMMAND: + return runWM_COMMAND(wParam, lParam, lResult); + case WM_NOTIFY: + return runWM_NOTIFY(wParam, lParam, lResult); + case WM_HSCROLL: + return runWM_HSCROLL(wParam, lParam, lResult); + case WM_CTLCOLORSTATIC: + case WM_CTLCOLORBTN: + if (parentBrush != NULL) + if (DeleteObject(parentBrush) == 0) + logLastError(L"error deleting old background brush()"); // but continue anyway; we will leak a brush but whatever + if (SetBkMode((HDC) wParam, TRANSPARENT) == 0) + logLastError(L"error setting transparent background mode to controls"); // but continue anyway; text will be wrong + parentBrush = getControlBackgroundBrush((HWND) lParam, (HDC) wParam); + if (parentBrush == NULL) // failed; just do default behavior + return FALSE; + *lResult = (LRESULT) parentBrush; + return TRUE; + } + return FALSE; +} diff --git a/dep/libui/windows/progressbar.cpp b/dep/libui/windows/progressbar.cpp new file mode 100644 index 0000000..c3a67dd --- /dev/null +++ b/dep/libui/windows/progressbar.cpp @@ -0,0 +1,83 @@ +// 19 may 2015 +#include "uipriv_windows.hpp" + +struct uiProgressBar { + uiWindowsControl c; + HWND hwnd; +}; + +uiWindowsControlAllDefaults(uiProgressBar) + +// via http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing +#define pbarWidth 237 +#define pbarHeight 8 + +static void uiProgressBarMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + uiProgressBar *p = uiProgressBar(c); + uiWindowsSizing sizing; + int x, y; + + x = pbarWidth; + y = pbarHeight; + uiWindowsGetSizing(p->hwnd, &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, &x, &y); + *width = x; + *height = y; +} + +#define indeterminate(p) ((getStyle(p->hwnd) & PBS_MARQUEE) != 0) + +int uiProgressBarValue(uiProgressBar *p) +{ + if (indeterminate(p)) + return -1; + return SendMessage(p->hwnd, PBM_GETPOS, 0, 0); +} + +// unfortunately, as of Vista progress bars have a forced animation on increase +// we have to set the progress bar to value + 1 and decrease it back to value if we want an "instant" change +// see http://stackoverflow.com/questions/2217688/windows-7-aero-theme-progress-bar-bug +// it's not ideal/perfect, but it will have to do +void uiProgressBarSetValue(uiProgressBar *p, int value) +{ + if (value == -1) { + if (!indeterminate(p)) { + setStyle(p->hwnd, getStyle(p->hwnd) | PBS_MARQUEE); + SendMessageW(p->hwnd, PBM_SETMARQUEE, (WPARAM) TRUE, 0); + } + return; + } + if (indeterminate(p)) { + SendMessageW(p->hwnd, PBM_SETMARQUEE, (WPARAM) FALSE, 0); + setStyle(p->hwnd, getStyle(p->hwnd) & ~PBS_MARQUEE); + } + + if (value < 0 || value > 100) + uiprivUserBug("Value %d is out of range for uiProgressBars.", value); + + if (value == 100) { // because we can't 101 + SendMessageW(p->hwnd, PBM_SETRANGE32, 0, 101); + SendMessageW(p->hwnd, PBM_SETPOS, 101, 0); + SendMessageW(p->hwnd, PBM_SETPOS, 100, 0); + SendMessageW(p->hwnd, PBM_SETRANGE32, 0, 100); + return; + } + SendMessageW(p->hwnd, PBM_SETPOS, (WPARAM) (value + 1), 0); + SendMessageW(p->hwnd, PBM_SETPOS, (WPARAM) value, 0); +} + +uiProgressBar *uiNewProgressBar(void) +{ + uiProgressBar *p; + + uiWindowsNewControl(uiProgressBar, p); + + p->hwnd = uiWindowsEnsureCreateControlHWND(0, + PROGRESS_CLASSW, L"", + PBS_SMOOTH, + hInstance, NULL, + FALSE); + + return p; +} diff --git a/dep/libui/windows/radiobuttons.cpp b/dep/libui/windows/radiobuttons.cpp new file mode 100644 index 0000000..0684a27 --- /dev/null +++ b/dep/libui/windows/radiobuttons.cpp @@ -0,0 +1,196 @@ +// 20 may 2015 +#include "uipriv_windows.hpp" + +// desired behavior: +// - tab moves between the radio buttons and the adjacent controls +// - arrow keys navigate between radio buttons +// - arrow keys do not leave the radio buttons (this is done in control.c) +// - arrow keys wrap around bare groups (if the previous control has WS_GROUP but the first radio button doesn't, then it doesn't; since our radio buttons are all in their own child window we can't do that) +// - clicking on a radio button draws a focus rect (TODO) + +struct uiRadioButtons { + uiWindowsControl c; + HWND hwnd; // of the container + std::vector *hwnds; // of the buttons + void (*onSelected)(uiRadioButtons *, void *); + void *onSelectedData; +}; + +static BOOL onWM_COMMAND(uiControl *c, HWND clicked, WORD code, LRESULT *lResult) +{ + uiRadioButtons *r = uiRadioButtons(c); + WPARAM check; + + if (code != BN_CLICKED) + return FALSE; + for (const HWND &hwnd : *(r->hwnds)) { + check = BST_UNCHECKED; + if (clicked == hwnd) + check = BST_CHECKED; + SendMessage(hwnd, BM_SETCHECK, check, 0); + } + (*(r->onSelected))(r, r->onSelectedData); + *lResult = 0; + return TRUE; +} + +static void defaultOnSelected(uiRadioButtons *r, void *data) +{ + // do nothing +} + +static void uiRadioButtonsDestroy(uiControl *c) +{ + uiRadioButtons *r = uiRadioButtons(c); + + for (const HWND &hwnd : *(r->hwnds)) { + uiWindowsUnregisterWM_COMMANDHandler(hwnd); + uiWindowsEnsureDestroyWindow(hwnd); + } + delete r->hwnds; + uiWindowsEnsureDestroyWindow(r->hwnd); + uiFreeControl(uiControl(r)); +} + +// TODO SyncEnableState +uiWindowsControlAllDefaultsExceptDestroy(uiRadioButtons) + +// from http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing +#define radiobuttonHeight 10 +// from http://msdn.microsoft.com/en-us/library/windows/desktop/bb226818%28v=vs.85%29.aspx +#define radiobuttonXFromLeftOfBoxToLeftOfLabel 12 + +static void uiRadioButtonsMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + uiRadioButtons *r = uiRadioButtons(c); + int wid, maxwid; + uiWindowsSizing sizing; + int x, y; + + if (r->hwnds->size() == 0) { + *width = 0; + *height = 0; + return; + } + maxwid = 0; + for (const HWND &hwnd : *(r->hwnds)) { + wid = uiWindowsWindowTextWidth(hwnd); + if (maxwid < wid) + maxwid = wid; + } + + x = radiobuttonXFromLeftOfBoxToLeftOfLabel; + y = radiobuttonHeight; + uiWindowsGetSizing((*(r->hwnds))[0], &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, &x, &y); + + *width = x + maxwid; + *height = y * r->hwnds->size(); +} + +static void radiobuttonsRelayout(uiRadioButtons *r) +{ + RECT client; + int x, y, width, height; + int height1; + uiWindowsSizing sizing; + + if (r->hwnds->size() == 0) + return; + uiWindowsEnsureGetClientRect(r->hwnd, &client); + x = client.left; + y = client.top; + width = client.right - client.left; + height1 = radiobuttonHeight; + uiWindowsGetSizing((*(r->hwnds))[0], &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, NULL, &height1); + height = height1; + for (const HWND &hwnd : *(r->hwnds)) { + uiWindowsEnsureMoveWindowDuringResize(hwnd, x, y, width, height); + y += height; + } +} + +static void radiobuttonsArrangeChildren(uiRadioButtons *r) +{ + LONG_PTR controlID; + HWND insertAfter; + + controlID = 100; + insertAfter = NULL; + for (const HWND &hwnd : *(r->hwnds)) + uiWindowsEnsureAssignControlIDZOrder(hwnd, &controlID, &insertAfter); +} + +void uiRadioButtonsAppend(uiRadioButtons *r, const char *text) +{ + HWND hwnd; + WCHAR *wtext; + DWORD groupTabStop; + + // the first radio button gets both WS_GROUP and WS_TABSTOP + // successive radio buttons get *neither* + groupTabStop = 0; + if (r->hwnds->size() == 0) + groupTabStop = WS_GROUP | WS_TABSTOP; + + wtext = toUTF16(text); + hwnd = uiWindowsEnsureCreateControlHWND(0, + L"button", wtext, + BS_RADIOBUTTON | groupTabStop, + hInstance, NULL, + TRUE); + uiprivFree(wtext); + uiWindowsEnsureSetParentHWND(hwnd, r->hwnd); + uiWindowsRegisterWM_COMMANDHandler(hwnd, onWM_COMMAND, uiControl(r)); + r->hwnds->push_back(hwnd); + radiobuttonsArrangeChildren(r); + uiWindowsControlMinimumSizeChanged(uiWindowsControl(r)); +} + +int uiRadioButtonsSelected(uiRadioButtons *r) +{ + size_t i; + + for (i = 0; i < r->hwnds->size(); i++) + if (SendMessage((*(r->hwnds))[i], BM_GETCHECK, 0, 0) == BST_CHECKED) + return i; + return -1; +} + +void uiRadioButtonsSetSelected(uiRadioButtons *r, int n) +{ + int m; + + m = uiRadioButtonsSelected(r); + if (m != -1) + SendMessage((*(r->hwnds))[m], BM_SETCHECK, BST_UNCHECKED, 0); + if (n != -1) + SendMessage((*(r->hwnds))[n], BM_SETCHECK, BST_CHECKED, 0); +} + +void uiRadioButtonsOnSelected(uiRadioButtons *r, void (*f)(uiRadioButtons *, void *), void *data) +{ + r->onSelected = f; + r->onSelectedData = data; +} + +static void onResize(uiWindowsControl *c) +{ + radiobuttonsRelayout(uiRadioButtons(c)); +} + +uiRadioButtons *uiNewRadioButtons(void) +{ + uiRadioButtons *r; + + uiWindowsNewControl(uiRadioButtons, r); + + r->hwnd = uiWindowsMakeContainer(uiWindowsControl(r), onResize); + + r->hwnds = new std::vector; + + uiRadioButtonsOnSelected(r, defaultOnSelected, NULL); + + return r; +} diff --git a/dep/libui/windows/resources.hpp b/dep/libui/windows/resources.hpp new file mode 100644 index 0000000..4ae5472 --- /dev/null +++ b/dep/libui/windows/resources.hpp @@ -0,0 +1,37 @@ +// 30 may 2015 + +#define rcTabPageDialog 29000 +#define rcFontDialog 29001 +#define rcColorDialog 29002 + +// TODO normalize these + +#define rcFontFamilyCombobox 1000 +#define rcFontStyleCombobox 1001 +#define rcFontSizeCombobox 1002 +#define rcFontSamplePlacement 1003 + +#define rcColorSVChooser 1100 +#define rcColorHSlider 1101 +#define rcPreview 1102 +#define rcOpacitySlider 1103 +#define rcH 1104 +#define rcS 1105 +#define rcV 1106 +#define rcRDouble 1107 +#define rcRInt 1108 +#define rcGDouble 1109 +#define rcGInt 1110 +#define rcBDouble 1111 +#define rcBInt 1112 +#define rcADouble 1113 +#define rcAInt 1114 +#define rcHex 1115 +#define rcHLabel 1116 +#define rcSLabel 1117 +#define rcVLabel 1118 +#define rcRLabel 1119 +#define rcGLabel 1120 +#define rcBLabel 1121 +#define rcALabel 1122 +#define rcHexLabel 1123 diff --git a/dep/libui/windows/resources.rc b/dep/libui/windows/resources.rc new file mode 100644 index 0000000..2ce7ee5 --- /dev/null +++ b/dep/libui/windows/resources.rc @@ -0,0 +1,13 @@ +// 30 may 2015 +#include "winapi.hpp" +#include "resources.hpp" + +// this is a UTF-8 file +#pragma code_page(65001) + +// this is the Common Controls 6 manifest +// we only define it in a shared build; static builds have to include the appropriate parts of the manifest in the output executable +// LONGTERM set up the string values here +#ifndef _UI_STATIC +ISOLATIONAWARE_MANIFEST_RESOURCE_ID RT_MANIFEST "libui.manifest" +#endif diff --git a/dep/libui/windows/separator.cpp b/dep/libui/windows/separator.cpp new file mode 100644 index 0000000..28e77e8 --- /dev/null +++ b/dep/libui/windows/separator.cpp @@ -0,0 +1,73 @@ +// 20 may 2015 +#include "uipriv_windows.hpp" + +// TODO +// - font scaling issues? https://www.viksoe.dk/code/bevelline.htm +// - isn't something in vista app guidelines suggesting this too? or some other microsoft doc? and what about VS itself? + +// references: +// - http://stackoverflow.com/questions/2892703/how-do-i-draw-separators +// - https://msdn.microsoft.com/en-us/library/windows/desktop/dn742405%28v=vs.85%29.aspx + +struct uiSeparator { + uiWindowsControl c; + HWND hwnd; + BOOL vertical; +}; + +uiWindowsControlAllDefaults(uiSeparator) + +// via https://msdn.microsoft.com/en-us/library/windows/desktop/bb226818%28v=vs.85%29.aspx +#define separatorHeight 1 + +// TODO +#define separatorWidth 1 + +static void uiSeparatorMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + uiSeparator *s = uiSeparator(c); + uiWindowsSizing sizing; + int x, y; + + *width = 1; // TODO + *height = 1; + x = separatorWidth; + y = separatorHeight; + uiWindowsGetSizing(s->hwnd, &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, &x, &y); + if (s->vertical) + *width = x; + else + *height = y; +} + +uiSeparator *uiNewHorizontalSeparator(void) +{ + uiSeparator *s; + + uiWindowsNewControl(uiSeparator, s); + + s->hwnd = uiWindowsEnsureCreateControlHWND(0, + L"static", L"", + SS_ETCHEDHORZ, + hInstance, NULL, + TRUE); + + return s; +} + +uiSeparator *uiNewVerticalSeparator(void) +{ + uiSeparator *s; + + uiWindowsNewControl(uiSeparator, s); + + s->hwnd = uiWindowsEnsureCreateControlHWND(0, + L"static", L"", + SS_ETCHEDHORZ, + hInstance, NULL, + TRUE); + s->vertical = TRUE; + + return s; +} diff --git a/dep/libui/windows/sizing.cpp b/dep/libui/windows/sizing.cpp new file mode 100644 index 0000000..33cc00b --- /dev/null +++ b/dep/libui/windows/sizing.cpp @@ -0,0 +1,63 @@ +// 14 may 2015 +#include "uipriv_windows.hpp" + +// TODO rework the error handling +void getSizing(HWND hwnd, uiWindowsSizing *sizing, HFONT font) +{ + HDC dc; + HFONT prevfont; + TEXTMETRICW tm; + SIZE size; + + dc = GetDC(hwnd); + if (dc == NULL) + logLastError(L"error getting DC"); + prevfont = (HFONT) SelectObject(dc, font); + if (prevfont == NULL) + logLastError(L"error loading control font into device context"); + + ZeroMemory(&tm, sizeof (TEXTMETRICW)); + if (GetTextMetricsW(dc, &tm) == 0) + logLastError(L"error getting text metrics"); + if (GetTextExtentPoint32W(dc, L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 52, &size) == 0) + logLastError(L"error getting text extent point"); + + sizing->BaseX = (int) ((size.cx / 26 + 1) / 2); + sizing->BaseY = (int) tm.tmHeight; + sizing->InternalLeading = tm.tmInternalLeading; + + if (SelectObject(dc, prevfont) != font) + logLastError(L"error restoring previous font into device context"); + if (ReleaseDC(hwnd, dc) == 0) + logLastError(L"error releasing DC"); +} + +void uiWindowsGetSizing(HWND hwnd, uiWindowsSizing *sizing) +{ + return getSizing(hwnd, sizing, hMessageFont); +} + +#define dlgUnitsToX(dlg, baseX) MulDiv((dlg), (baseX), 4) +#define dlgUnitsToY(dlg, baseY) MulDiv((dlg), (baseY), 8) + +void uiWindowsSizingDlgUnitsToPixels(uiWindowsSizing *sizing, int *x, int *y) +{ + if (x != NULL) + *x = dlgUnitsToX(*x, sizing->BaseX); + if (y != NULL) + *y = dlgUnitsToY(*y, sizing->BaseY); +} + +// from https://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing and https://msdn.microsoft.com/en-us/library/windows/desktop/bb226818%28v=vs.85%29.aspx +// this X value is really only for buttons but I don't see a better one :/ +#define winXPadding 4 +// TODO is this too much? +#define winYPadding 4 + +void uiWindowsSizingStandardPadding(uiWindowsSizing *sizing, int *x, int *y) +{ + if (x != NULL) + *x = dlgUnitsToX(winXPadding, sizing->BaseX); + if (y != NULL) + *y = dlgUnitsToY(winYPadding, sizing->BaseY); +} diff --git a/dep/libui/windows/slider.cpp b/dep/libui/windows/slider.cpp new file mode 100644 index 0000000..5c671dd --- /dev/null +++ b/dep/libui/windows/slider.cpp @@ -0,0 +1,98 @@ +// 20 may 2015 +#include "uipriv_windows.hpp" + +struct uiSlider { + uiWindowsControl c; + HWND hwnd; + void (*onChanged)(uiSlider *, void *); + void *onChangedData; +}; + +static BOOL onWM_HSCROLL(uiControl *c, HWND hwnd, WORD code, LRESULT *lResult) +{ + uiSlider *s = uiSlider(c); + + (*(s->onChanged))(s, s->onChangedData); + *lResult = 0; + return TRUE; +} + +static void uiSliderDestroy(uiControl *c) +{ + uiSlider *s = uiSlider(c); + + uiWindowsUnregisterWM_HSCROLLHandler(s->hwnd); + uiWindowsEnsureDestroyWindow(s->hwnd); + uiFreeControl(uiControl(s)); +} + +uiWindowsControlAllDefaultsExceptDestroy(uiSlider); + +// from http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing +#define sliderWidth 107 /* this is actually the shorter progress bar width, but Microsoft doesn't indicate a width */ +#define sliderHeight 15 + +static void uiSliderMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + uiSlider *s = uiSlider(c); + uiWindowsSizing sizing; + int x, y; + + x = sliderWidth; + y = sliderHeight; + uiWindowsGetSizing(s->hwnd, &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, &x, &y); + *width = x; + *height = y; +} + +static void defaultOnChanged(uiSlider *s, void *data) +{ + // do nothing +} + +int uiSliderValue(uiSlider *s) +{ + return SendMessageW(s->hwnd, TBM_GETPOS, 0, 0); +} + +void uiSliderSetValue(uiSlider *s, int value) +{ + // don't use TBM_SETPOSNOTIFY; that triggers an event + SendMessageW(s->hwnd, TBM_SETPOS, (WPARAM) TRUE, (LPARAM) value); +} + +void uiSliderOnChanged(uiSlider *s, void (*f)(uiSlider *, void *), void *data) +{ + s->onChanged = f; + s->onChangedData = data; +} + +uiSlider *uiNewSlider(int min, int max) +{ + uiSlider *s; + int temp; + + if (min >= max) { + temp = min; + min = max; + max = temp; + } + + uiWindowsNewControl(uiSlider, s); + + s->hwnd = uiWindowsEnsureCreateControlHWND(0, + TRACKBAR_CLASSW, L"", + TBS_HORZ | TBS_TOOLTIPS | TBS_TRANSPARENTBKGND | WS_TABSTOP, + hInstance, NULL, + TRUE); + + uiWindowsRegisterWM_HSCROLLHandler(s->hwnd, onWM_HSCROLL, uiControl(s)); + uiSliderOnChanged(s, defaultOnChanged, NULL); + + SendMessageW(s->hwnd, TBM_SETRANGEMIN, (WPARAM) TRUE, (LPARAM) min); + SendMessageW(s->hwnd, TBM_SETRANGEMAX, (WPARAM) TRUE, (LPARAM) max); + SendMessageW(s->hwnd, TBM_SETPOS, (WPARAM) TRUE, (LPARAM) min); + + return s; +} diff --git a/dep/libui/windows/spinbox.cpp b/dep/libui/windows/spinbox.cpp new file mode 100644 index 0000000..57fb8d6 --- /dev/null +++ b/dep/libui/windows/spinbox.cpp @@ -0,0 +1,216 @@ +// 8 april 2015 +#include "uipriv_windows.hpp" + +struct uiSpinbox { + uiWindowsControl c; + HWND hwnd; + HWND edit; + HWND updown; + void (*onChanged)(uiSpinbox *, void *); + void *onChangedData; + BOOL inhibitChanged; +}; + +// utility functions + +static int value(uiSpinbox *s) +{ + BOOL neededCap = FALSE; + LRESULT val; + + // This verifies the value put in, capping it automatically. + // We don't need to worry about checking for an error; that flag should really be called "did we have to cap?". + // We DO need to set the value in case of a cap though. + val = SendMessageW(s->updown, UDM_GETPOS32, 0, (LPARAM) (&neededCap)); + if (neededCap) { + s->inhibitChanged = TRUE; + SendMessageW(s->updown, UDM_SETPOS32, 0, (LPARAM) val); + s->inhibitChanged = FALSE; + } + return val; +} + +// control implementation + +// TODO assign lResult +static BOOL onWM_COMMAND(uiControl *c, HWND hwnd, WORD code, LRESULT *lResult) +{ + uiSpinbox *s = (uiSpinbox *) c; + WCHAR *wtext; + + if (code != EN_CHANGE) + return FALSE; + if (s->inhibitChanged) + return FALSE; + // We want to allow typing negative numbers; the natural way to do so is to start with a -. + // However, if we just have the code below, the up-down will catch the bare - and reject it. + // Let's fix that. + // This won't handle leading spaces, but spaces aren't allowed *anyway*. + wtext = windowText(s->edit); + if (wcscmp(wtext, L"-") == 0) { + uiprivFree(wtext); + return TRUE; + } + uiprivFree(wtext); + // value() does the work for us + value(s); + (*(s->onChanged))(s, s->onChangedData); + return TRUE; +} + +static void uiSpinboxDestroy(uiControl *c) +{ + uiSpinbox *s = uiSpinbox(c); + + uiWindowsUnregisterWM_COMMANDHandler(s->edit); + uiWindowsEnsureDestroyWindow(s->updown); + uiWindowsEnsureDestroyWindow(s->edit); + uiWindowsEnsureDestroyWindow(s->hwnd); + uiFreeControl(uiControl(s)); +} + +// TODO SyncEnableState +uiWindowsControlAllDefaultsExceptDestroy(uiSpinbox) + +// from http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing +// TODO reduce this? +#define entryWidth 107 /* this is actually the shorter progress bar width, but Microsoft only indicates as wide as necessary */ +#define entryHeight 14 + +static void uiSpinboxMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + uiSpinbox *s = uiSpinbox(c); + uiWindowsSizing sizing; + int x, y; + + x = entryWidth; + y = entryHeight; + // note that we go by the edit here + uiWindowsGetSizing(s->edit, &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, &x, &y); + *width = x; + *height = y; +} + +static void spinboxArrangeChildren(uiSpinbox *s) +{ + LONG_PTR controlID; + HWND insertAfter; + + controlID = 100; + insertAfter = NULL; + uiWindowsEnsureAssignControlIDZOrder(s->edit, &controlID, &insertAfter); + uiWindowsEnsureAssignControlIDZOrder(s->updown, &controlID, &insertAfter); +} + +// an up-down control will only properly position itself the first time +// stupidly, there are no messages to force a size calculation, nor can I seem to reset the buddy window to force a new position +// alas, we have to make a new up/down control each time :( +static void recreateUpDown(uiSpinbox *s) +{ + BOOL preserve = FALSE; + int current; + // Microsoft's commctrl.h says to use this type + INT min, max; + + if (s->updown != NULL) { + preserve = TRUE; + current = value(s); + SendMessageW(s->updown, UDM_GETRANGE32, (WPARAM) (&min), (LPARAM) (&max)); + uiWindowsEnsureDestroyWindow(s->updown); + } + s->inhibitChanged = TRUE; + s->updown = CreateWindowExW(0, + UPDOWN_CLASSW, L"", + // no WS_VISIBLE; we set visibility ourselves + // up-down control should not be a tab stop + WS_CHILD | UDS_ALIGNRIGHT | UDS_ARROWKEYS | UDS_HOTTRACK | UDS_NOTHOUSANDS | UDS_SETBUDDYINT, + // this is important; it's necessary for autosizing to work + 0, 0, 0, 0, + s->hwnd, NULL, hInstance, NULL); + if (s->updown == NULL) + logLastError(L"error creating updown"); + SendMessageW(s->updown, UDM_SETBUDDY, (WPARAM) (s->edit), 0); + if (preserve) { + SendMessageW(s->updown, UDM_SETRANGE32, (WPARAM) min, (LPARAM) max); + SendMessageW(s->updown, UDM_SETPOS32, 0, (LPARAM) current); + } + // preserve the Z-order + spinboxArrangeChildren(s); + // TODO properly show/enable + ShowWindow(s->updown, SW_SHOW); + s->inhibitChanged = FALSE; +} + +static void spinboxRelayout(uiSpinbox *s) +{ + RECT r; + + // make the edit fill the container first; the new updown will resize it + uiWindowsEnsureGetClientRect(s->hwnd, &r); + uiWindowsEnsureMoveWindowDuringResize(s->edit, r.left, r.top, r.right - r.left, r.bottom - r.top); + recreateUpDown(s); +} + +static void defaultOnChanged(uiSpinbox *s, void *data) +{ + // do nothing +} + +int uiSpinboxValue(uiSpinbox *s) +{ + return value(s); +} + +void uiSpinboxSetValue(uiSpinbox *s, int value) +{ + s->inhibitChanged = TRUE; + SendMessageW(s->updown, UDM_SETPOS32, 0, (LPARAM) value); + s->inhibitChanged = FALSE; +} + +void uiSpinboxOnChanged(uiSpinbox *s, void (*f)(uiSpinbox *, void *), void *data) +{ + s->onChanged = f; + s->onChangedData = data; +} + +static void onResize(uiWindowsControl *c) +{ + spinboxRelayout(uiSpinbox(c)); +} + +uiSpinbox *uiNewSpinbox(int min, int max) +{ + uiSpinbox *s; + int temp; + + if (min >= max) { + temp = min; + min = max; + max = temp; + } + + uiWindowsNewControl(uiSpinbox, s); + + s->hwnd = uiWindowsMakeContainer(uiWindowsControl(s), onResize); + + s->edit = uiWindowsEnsureCreateControlHWND(WS_EX_CLIENTEDGE, + L"edit", L"", + // don't use ES_NUMBER; it doesn't allow typing in a leading - + ES_AUTOHSCROLL | ES_LEFT | ES_NOHIDESEL | WS_TABSTOP, + hInstance, NULL, + TRUE); + uiWindowsEnsureSetParentHWND(s->edit, s->hwnd); + + uiWindowsRegisterWM_COMMANDHandler(s->edit, onWM_COMMAND, uiControl(s)); + uiSpinboxOnChanged(s, defaultOnChanged, NULL); + + recreateUpDown(s); + s->inhibitChanged = TRUE; + SendMessageW(s->updown, UDM_SETRANGE32, (WPARAM) min, (LPARAM) max); + SendMessageW(s->updown, UDM_SETPOS32, 0, (LPARAM) min); + s->inhibitChanged = FALSE; + + return s; +} diff --git a/dep/libui/windows/stddialogs.cpp b/dep/libui/windows/stddialogs.cpp new file mode 100644 index 0000000..c6ac455 --- /dev/null +++ b/dep/libui/windows/stddialogs.cpp @@ -0,0 +1,133 @@ +// 22 may 2015 +#include "uipriv_windows.hpp" + +// TODO document all this is what we want +// TODO do the same for font and color buttons + +// notes: +// - FOS_SUPPORTSTREAMABLEITEMS doesn't seem to be supported on windows vista, or at least not with the flags we use +// - even with FOS_NOVALIDATE the dialogs will reject invalid filenames (at least on Vista, anyway) +// - lack of FOS_NOREADONLYRETURN doesn't seem to matter on Windows 7 + +// TODO +// - http://blogs.msdn.com/b/wpfsdk/archive/2006/10/26/uncommon-dialogs--font-chooser-and-color-picker-dialogs.aspx +// - when a dialog is active, tab navigation in other windows stops working +// - when adding uiOpenFolder(), use IFileDialog as well - https://msdn.microsoft.com/en-us/library/windows/desktop/bb762115%28v=vs.85%29.aspx + +#define windowHWND(w) ((HWND) uiControlHandle(uiControl(w))) + +char *commonItemDialog(HWND parent, REFCLSID clsid, REFIID iid, FILEOPENDIALOGOPTIONS optsadd) +{ + IFileDialog *d = NULL; + FILEOPENDIALOGOPTIONS opts; + IShellItem *result = NULL; + WCHAR *wname = NULL; + char *name = NULL; + HRESULT hr; + + hr = CoCreateInstance(clsid, + NULL, CLSCTX_INPROC_SERVER, + iid, (LPVOID *) (&d)); + if (hr != S_OK) { + logHRESULT(L"error creating common item dialog", hr); + // always return NULL on error + goto out; + } + hr = d->GetOptions(&opts); + if (hr != S_OK) { + logHRESULT(L"error getting current options", hr); + goto out; + } + opts |= optsadd; + // the other platforms don't check read-only; we won't either + opts &= ~FOS_NOREADONLYRETURN; + hr = d->SetOptions(opts); + if (hr != S_OK) { + logHRESULT(L"error setting options", hr); + goto out; + } + hr = d->Show(parent); + if (hr == HRESULT_FROM_WIN32(ERROR_CANCELLED)) + // cancelled; return NULL like we have ready + goto out; + if (hr != S_OK) { + logHRESULT(L"error showing dialog", hr); + goto out; + } + hr = d->GetResult(&result); + if (hr != S_OK) { + logHRESULT(L"error getting dialog result", hr); + goto out; + } + hr = result->GetDisplayName(SIGDN_FILESYSPATH, &wname); + if (hr != S_OK) { + logHRESULT(L"error getting filename", hr); + goto out; + } + name = toUTF8(wname); + +out: + if (wname != NULL) + CoTaskMemFree(wname); + if (result != NULL) + result->Release(); + if (d != NULL) + d->Release(); + return name; +} + +char *uiOpenFile(uiWindow *parent) +{ + char *res; + + disableAllWindowsExcept(parent); + res = commonItemDialog(windowHWND(parent), + CLSID_FileOpenDialog, IID_IFileOpenDialog, + FOS_NOCHANGEDIR | FOS_ALLNONSTORAGEITEMS | FOS_NOVALIDATE | FOS_PATHMUSTEXIST | FOS_FILEMUSTEXIST | FOS_SHAREAWARE | FOS_NOTESTFILECREATE | FOS_NODEREFERENCELINKS | FOS_FORCESHOWHIDDEN | FOS_DEFAULTNOMINIMODE); + enableAllWindowsExcept(parent); + return res; +} + +char *uiSaveFile(uiWindow *parent) +{ + char *res; + + disableAllWindowsExcept(parent); + res = commonItemDialog(windowHWND(parent), + CLSID_FileSaveDialog, IID_IFileSaveDialog, + FOS_OVERWRITEPROMPT | FOS_NOCHANGEDIR | FOS_ALLNONSTORAGEITEMS | FOS_NOVALIDATE | FOS_SHAREAWARE | FOS_NOTESTFILECREATE | FOS_NODEREFERENCELINKS | FOS_FORCESHOWHIDDEN | FOS_DEFAULTNOMINIMODE); + enableAllWindowsExcept(parent); + return res; +} + +// TODO switch to TaskDialogIndirect()? + +static void msgbox(HWND parent, const char *title, const char *description, TASKDIALOG_COMMON_BUTTON_FLAGS buttons, PCWSTR icon) +{ + WCHAR *wtitle, *wdescription; + HRESULT hr; + + wtitle = toUTF16(title); + wdescription = toUTF16(description); + + hr = TaskDialog(parent, NULL, NULL, wtitle, wdescription, buttons, icon, NULL); + if (hr != S_OK) + logHRESULT(L"error showing task dialog", hr); + + uiprivFree(wdescription); + uiprivFree(wtitle); +} + +void uiMsgBox(uiWindow *parent, const char *title, const char *description) +{ + disableAllWindowsExcept(parent); + msgbox(windowHWND(parent), title, description, TDCBF_OK_BUTTON, NULL); + enableAllWindowsExcept(parent); +} + +void uiMsgBoxError(uiWindow *parent, const char *title, const char *description) +{ + disableAllWindowsExcept(parent); + msgbox(windowHWND(parent), title, description, TDCBF_OK_BUTTON, TD_ERROR_ICON); + enableAllWindowsExcept(parent); +} diff --git a/dep/libui/windows/tab.cpp b/dep/libui/windows/tab.cpp new file mode 100644 index 0000000..e723958 --- /dev/null +++ b/dep/libui/windows/tab.cpp @@ -0,0 +1,287 @@ +// 16 may 2015 +#include "uipriv_windows.hpp" + +// You don't add controls directly to a tab control on Windows; instead you make them siblings and swap between them on a TCN_SELCHANGING/TCN_SELCHANGE notification pair. +// In addition, you use dialogs because they can be textured properly; other controls cannot. (Things will look wrong if the tab background in the current theme is fancy if you just use the tab background by itself; see http://stackoverflow.com/questions/30087540/why-are-my-programss-tab-controls-rendering-their-background-in-a-blocky-way-b.) + +struct uiTab { + uiWindowsControl c; + HWND hwnd; // of the outer container + HWND tabHWND; // of the tab control itself + std::vector *pages; + HWND parent; +}; + +// utility functions + +static LRESULT curpage(uiTab *t) +{ + return SendMessageW(t->tabHWND, TCM_GETCURSEL, 0, 0); +} + +static struct tabPage *tabPage(uiTab *t, int i) +{ + return (*(t->pages))[i]; +} + +static void tabPageRect(uiTab *t, RECT *r) +{ + // this rect needs to be in parent window coordinates, but TCM_ADJUSTRECT wants a window rect, which is screen coordinates + // because we have each page as a sibling of the tab, use the tab's own rect as the input rect + uiWindowsEnsureGetWindowRect(t->tabHWND, r); + SendMessageW(t->tabHWND, TCM_ADJUSTRECT, (WPARAM) FALSE, (LPARAM) r); + // and get it in terms of the container instead of the screen + mapWindowRect(NULL, t->hwnd, r); +} + +static void tabRelayout(uiTab *t) +{ + struct tabPage *page; + RECT r; + + // first move the tab control itself + uiWindowsEnsureGetClientRect(t->hwnd, &r); + uiWindowsEnsureMoveWindowDuringResize(t->tabHWND, r.left, r.top, r.right - r.left, r.bottom - r.top); + + // then the current page + if (t->pages->size() == 0) + return; + page = tabPage(t, curpage(t)); + tabPageRect(t, &r); + uiWindowsEnsureMoveWindowDuringResize(page->hwnd, r.left, r.top, r.right - r.left, r.bottom - r.top); +} + +static void showHidePage(uiTab *t, LRESULT which, int hide) +{ + struct tabPage *page; + + if (which == (LRESULT) (-1)) + return; + page = tabPage(t, which); + if (hide) + ShowWindow(page->hwnd, SW_HIDE); + else { + ShowWindow(page->hwnd, SW_SHOW); + // we only resize the current page, so we have to resize it; before we can do that, we need to make sure we are of the right size + uiWindowsControlMinimumSizeChanged(uiWindowsControl(t)); + } +} + +// control implementation + +static BOOL onWM_NOTIFY(uiControl *c, HWND hwnd, NMHDR *nm, LRESULT *lResult) +{ + uiTab *t = uiTab(c); + + if (nm->code != TCN_SELCHANGING && nm->code != TCN_SELCHANGE) + return FALSE; + showHidePage(t, curpage(t), nm->code == TCN_SELCHANGING); + *lResult = 0; + if (nm->code == TCN_SELCHANGING) + *lResult = FALSE; + return TRUE; +} + +static void uiTabDestroy(uiControl *c) +{ + uiTab *t = uiTab(c); + uiControl *child; + + for (struct tabPage *&page : *(t->pages)) { + child = page->child; + tabPageDestroy(page); + if (child != NULL) { + uiControlSetParent(child, NULL); + uiControlDestroy(child); + } + } + delete t->pages; + uiWindowsUnregisterWM_NOTIFYHandler(t->tabHWND); + uiWindowsEnsureDestroyWindow(t->tabHWND); + uiWindowsEnsureDestroyWindow(t->hwnd); + uiFreeControl(uiControl(t)); +} + +uiWindowsControlDefaultHandle(uiTab) +uiWindowsControlDefaultParent(uiTab) +uiWindowsControlDefaultSetParent(uiTab) +uiWindowsControlDefaultToplevel(uiTab) +uiWindowsControlDefaultVisible(uiTab) +uiWindowsControlDefaultShow(uiTab) +uiWindowsControlDefaultHide(uiTab) +uiWindowsControlDefaultEnabled(uiTab) +uiWindowsControlDefaultEnable(uiTab) +uiWindowsControlDefaultDisable(uiTab) + +static void uiTabSyncEnableState(uiWindowsControl *c, int enabled) +{ + uiTab *t = uiTab(c); + + if (uiWindowsShouldStopSyncEnableState(uiWindowsControl(t), enabled)) + return; + EnableWindow(t->tabHWND, enabled); + for (struct tabPage *&page : *(t->pages)) + if (page->child != NULL) + uiWindowsControlSyncEnableState(uiWindowsControl(page->child), enabled); +} + +uiWindowsControlDefaultSetParentHWND(uiTab) + +static void uiTabMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + uiTab *t = uiTab(c); + int pagewid, pageht; + struct tabPage *page; + RECT r; + + // only consider the current page + pagewid = 0; + pageht = 0; + if (t->pages->size() != 0) { + page = tabPage(t, curpage(t)); + tabPageMinimumSize(page, &pagewid, &pageht); + } + + r.left = 0; + r.top = 0; + r.right = pagewid; + r.bottom = pageht; + // this also includes the tabs themselves + SendMessageW(t->tabHWND, TCM_ADJUSTRECT, (WPARAM) TRUE, (LPARAM) (&r)); + *width = r.right - r.left; + *height = r.bottom - r.top; +} + +static void uiTabMinimumSizeChanged(uiWindowsControl *c) +{ + uiTab *t = uiTab(c); + + if (uiWindowsControlTooSmall(uiWindowsControl(t))) { + uiWindowsControlContinueMinimumSizeChanged(uiWindowsControl(t)); + return; + } + tabRelayout(t); +} + +uiWindowsControlDefaultLayoutRect(uiTab) +uiWindowsControlDefaultAssignControlIDZOrder(uiTab) + +static void uiTabChildVisibilityChanged(uiWindowsControl *c) +{ + // TODO eliminate the redundancy + uiWindowsControlMinimumSizeChanged(c); +} + +static void tabArrangePages(uiTab *t) +{ + LONG_PTR controlID = 100; + HWND insertAfter = NULL; + + // TODO is this first or last? + uiWindowsEnsureAssignControlIDZOrder(t->tabHWND, &controlID, &insertAfter); + for (struct tabPage *&page : *(t->pages)) + uiWindowsEnsureAssignControlIDZOrder(page->hwnd, &controlID, &insertAfter); +} + +void uiTabAppend(uiTab *t, const char *name, uiControl *child) +{ + uiTabInsertAt(t, name, t->pages->size(), child); +} + +void uiTabInsertAt(uiTab *t, const char *name, int n, uiControl *child) +{ + struct tabPage *page; + LRESULT hide, show; + TCITEMW item; + WCHAR *wname; + + // see below + hide = curpage(t); + + if (child != NULL) + uiControlSetParent(child, uiControl(t)); + + page = newTabPage(child); + uiWindowsEnsureSetParentHWND(page->hwnd, t->hwnd); + t->pages->insert(t->pages->begin() + n, page); + tabArrangePages(t); + + ZeroMemory(&item, sizeof (TCITEMW)); + item.mask = TCIF_TEXT; + wname = toUTF16(name); + item.pszText = wname; + if (SendMessageW(t->tabHWND, TCM_INSERTITEM, (WPARAM) n, (LPARAM) (&item)) == (LRESULT) -1) + logLastError(L"error adding tab to uiTab"); + uiprivFree(wname); + + // we need to do this because adding the first tab doesn't send a TCN_SELCHANGE; it just shows the page + show = curpage(t); + if (show != hide) { + showHidePage(t, hide, 1); + showHidePage(t, show, 0); + } +} + +void uiTabDelete(uiTab *t, int n) +{ + struct tabPage *page; + + // first delete the tab from the tab control + // if this is the current tab, no tab will be selected, which is good + if (SendMessageW(t->tabHWND, TCM_DELETEITEM, (WPARAM) n, 0) == FALSE) + logLastError(L"error deleting uiTab tab"); + + // now delete the page itself + page = tabPage(t, n); + if (page->child != NULL) + uiControlSetParent(page->child, NULL); + tabPageDestroy(page); + t->pages->erase(t->pages->begin() + n); +} + +int uiTabNumPages(uiTab *t) +{ + return t->pages->size(); +} + +int uiTabMargined(uiTab *t, int n) +{ + return tabPage(t, n)->margined; +} + +void uiTabSetMargined(uiTab *t, int n, int margined) +{ + struct tabPage *page; + + page = tabPage(t, n); + page->margined = margined; + // even if the page doesn't have a child it might still have a new minimum size with margins; this is the easiest way to verify it + uiWindowsControlMinimumSizeChanged(uiWindowsControl(t)); +} + +static void onResize(uiWindowsControl *c) +{ + tabRelayout(uiTab(c)); +} + +uiTab *uiNewTab(void) +{ + uiTab *t; + + uiWindowsNewControl(uiTab, t); + + t->hwnd = uiWindowsMakeContainer(uiWindowsControl(t), onResize); + + t->tabHWND = uiWindowsEnsureCreateControlHWND(0, + WC_TABCONTROLW, L"", + TCS_TOOLTIPS | WS_TABSTOP, + hInstance, NULL, + TRUE); + uiWindowsEnsureSetParentHWND(t->tabHWND, t->hwnd); + + uiWindowsRegisterWM_NOTIFYHandler(t->tabHWND, onWM_NOTIFY, uiControl(t)); + + t->pages = new std::vector; + + return t; +} diff --git a/dep/libui/windows/table.cpp b/dep/libui/windows/table.cpp new file mode 100644 index 0000000..85a51c1 --- /dev/null +++ b/dep/libui/windows/table.cpp @@ -0,0 +1,522 @@ +#include "uipriv_windows.hpp" +#include "table.hpp" + +// general TODOs: +// - tooltips don't work properly on columns with icons (the listview always thinks there's enough room for a short label because it's not taking the icon into account); is this a bug in our LVN_GETDISPINFO handler or something else? +// - should clicking on some other column of the same row, even one that doesn't edit, cancel editing? +// - implement keyboard accessibility +// - implement accessibility in general (Dynamic Annotations maybe?) +// - if I didn't handle these already: "drawing focus rects here, subitem navigation and activation with the keyboard" + +uiTableModel *uiNewTableModel(uiTableModelHandler *mh) +{ + uiTableModel *m; + + m = uiprivNew(uiTableModel); + m->mh = mh; + m->tables = new std::vector; + return m; +} + +void uiFreeTableModel(uiTableModel *m) +{ + delete m->tables; + uiprivFree(m); +} + +// TODO document that when this is called, the model must return the new row count when asked +void uiTableModelRowInserted(uiTableModel *m, int newIndex) +{ + LVITEMW item; + int newCount; + + newCount = uiprivTableModelNumRows(m); + ZeroMemory(&item, sizeof (LVITEMW)); + item.mask = 0; + item.iItem = newIndex; + item.iSubItem = 0; + for (auto t : *(m->tables)) { + // actually insert the rows + if (SendMessageW(t->hwnd, LVM_SETITEMCOUNT, (WPARAM) newCount, LVSICF_NOINVALIDATEALL) == 0) + logLastError(L"error calling LVM_SETITEMCOUNT in uiTableModelRowInserted()"); + // and redraw every row from the new row down to simulate adding it + if (SendMessageW(t->hwnd, LVM_REDRAWITEMS, (WPARAM) newIndex, (LPARAM) (newCount - 1)) == FALSE) + logLastError(L"error calling LVM_REDRAWITEMS in uiTableModelRowInserted()"); + + // update selection state + if (SendMessageW(t->hwnd, LVM_INSERTITEM, 0, (LPARAM) (&item)) == (LRESULT) (-1)) + logLastError(L"error calling LVM_INSERTITEM in uiTableModelRowInserted() to update selection state"); + } +} + +// TODO compare LVM_UPDATE and LVM_REDRAWITEMS +void uiTableModelRowChanged(uiTableModel *m, int index) +{ + for (auto t : *(m->tables)) + if (SendMessageW(t->hwnd, LVM_UPDATE, (WPARAM) index, 0) == (LRESULT) (-1)) + logLastError(L"error calling LVM_UPDATE in uiTableModelRowChanged()"); +} + +// TODO document that when this is called, the model must return the OLD row count when asked +// TODO for this and the above, see what GTK+ requires and adjust accordingly +void uiTableModelRowDeleted(uiTableModel *m, int oldIndex) +{ + int newCount; + + newCount = uiprivTableModelNumRows(m); + newCount--; + for (auto t : *(m->tables)) { + // update selection state + if (SendMessageW(t->hwnd, LVM_DELETEITEM, (WPARAM) oldIndex, 0) == (LRESULT) (-1)) + logLastError(L"error calling LVM_DELETEITEM in uiTableModelRowDeleted() to update selection state"); + + // actually delete the rows + if (SendMessageW(t->hwnd, LVM_SETITEMCOUNT, (WPARAM) newCount, LVSICF_NOINVALIDATEALL) == 0) + logLastError(L"error calling LVM_SETITEMCOUNT in uiTableModelRowDeleted()"); + // and redraw every row from the new nth row down to simulate removing the old nth row + if (SendMessageW(t->hwnd, LVM_REDRAWITEMS, (WPARAM) oldIndex, (LPARAM) (newCount - 1)) == FALSE) + logLastError(L"error calling LVM_REDRAWITEMS in uiTableModelRowDeleted()"); + } +} + +uiTableModelHandler *uiprivTableModelHandler(uiTableModel *m) +{ + return m->mh; +} + +// TODO explain all this +static LRESULT CALLBACK tableSubProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIDSubclass, DWORD_PTR dwRefData) +{ + uiTable *t = (uiTable *) dwRefData; + NMHDR *nmhdr = (NMHDR *) lParam; + bool finishEdit, abortEdit; + HWND header; + LRESULT lResult; + HRESULT hr; + + finishEdit = false; + abortEdit = false; + switch (uMsg) { + case WM_TIMER: + if (wParam == (WPARAM) (&(t->inDoubleClickTimer))) { + t->inDoubleClickTimer = FALSE; + // TODO check errors + KillTimer(hwnd, wParam); + return 0; + } + if (wParam != (WPARAM) t) + break; + // TODO only increment and update if visible? + for (auto &i : *(t->indeterminatePositions)) { + i.second++; + // TODO check errors + SendMessageW(hwnd, LVM_UPDATE, (WPARAM) (i.first.first), 0); + } + return 0; + case WM_LBUTTONDOWN: + t->inLButtonDown = TRUE; + lResult = DefSubclassProc(hwnd, uMsg, wParam, lParam); + t->inLButtonDown = FALSE; + return lResult; + case WM_COMMAND: + if (HIWORD(wParam) == EN_UPDATE) { + // the real list view resizes the edit control on this notification specifically + hr = uiprivTableResizeWhileEditing(t); + if (hr != S_OK) { + // TODO + } + break; + } + // the real list view accepts changes in this case + if (HIWORD(wParam) == EN_KILLFOCUS) + finishEdit = true; + break; // don't override default handling + case WM_NOTIFY: + // list view accepts changes on column resize, but does not provide such notifications :/ + header = (HWND) SendMessageW(t->hwnd, LVM_GETHEADER, 0, 0); + if (nmhdr->hwndFrom == header) { + NMHEADERW *nm = (NMHEADERW *) nmhdr; + + switch (nmhdr->code) { + case HDN_ITEMCHANGED: + if ((nm->pitem->mask & HDI_WIDTH) == 0) + break; + // fall through + case HDN_DIVIDERDBLCLICK: + case HDN_TRACK: + case HDN_ENDTRACK: + finishEdit = true; + } + } + // I think this mirrors the WM_COMMAND one above... TODO + if (nmhdr->code == NM_KILLFOCUS) + finishEdit = true; + break; // don't override default handling + case LVM_CANCELEDITLABEL: + finishEdit = true; + // TODO properly imitate notifiactions + break; // don't override default handling + // TODO finish edit on WM_WINDOWPOSCHANGING and WM_SIZE? + // for the next three: this item is about to go away; don't bother keeping changes + case LVM_SETITEMCOUNT: + if (wParam <= t->editedItem) + abortEdit = true; + break; // don't override default handling + case LVM_DELETEITEM: + if (wParam == t->editedItem) + abortEdit = true; + break; // don't override default handling + case LVM_DELETEALLITEMS: + abortEdit = true; + break; // don't override default handling + case WM_NCDESTROY: + if (RemoveWindowSubclass(hwnd, tableSubProc, uIDSubclass) == FALSE) + logLastError(L"RemoveWindowSubclass()"); + // fall through + } + if (finishEdit) { + hr = uiprivTableFinishEditingText(t); + if (hr != S_OK) { + // TODO + } + } else if (abortEdit) { + hr = uiprivTableAbortEditingText(t); + if (hr != S_OK) { + // TODO + } + } + return DefSubclassProc(hwnd, uMsg, wParam, lParam); +} + +int uiprivTableProgress(uiTable *t, int item, int subitem, int modelColumn, LONG *pos) +{ + uiTableValue *value; + int progress; + std::pair p; + std::map, LONG>::iterator iter; + bool startTimer = false; + bool stopTimer = false; + + value = uiprivTableModelCellValue(t->model, item, modelColumn); + progress = uiTableValueInt(value); + uiFreeTableValue(value); + + p.first = item; + p.second = subitem; + iter = t->indeterminatePositions->find(p); + if (iter == t->indeterminatePositions->end()) { + if (progress == -1) { + startTimer = t->indeterminatePositions->size() == 0; + (*(t->indeterminatePositions))[p] = 0; + if (pos != NULL) + *pos = 0; + } + } else + if (progress != -1) { + t->indeterminatePositions->erase(p); + stopTimer = t->indeterminatePositions->size() == 0; + } else if (pos != NULL) + *pos = iter->second; + + if (startTimer) + // the interval shown here is PBM_SETMARQUEE's default + // TODO should we pass a function here instead? it seems to be called by DispatchMessage(), not DefWindowProc(), but I'm still unsure + if (SetTimer(t->hwnd, (UINT_PTR) t, 30, NULL) == 0) + logLastError(L"SetTimer()"); + if (stopTimer) + if (KillTimer(t->hwnd, (UINT_PTR) (&t)) == 0) + logLastError(L"KillTimer()"); + + return progress; +} + +// TODO properly integrate compound statements +static BOOL onWM_NOTIFY(uiControl *c, HWND hwnd, NMHDR *nmhdr, LRESULT *lResult) +{ + uiTable *t = uiTable(c); + HRESULT hr; + + switch (nmhdr->code) { + case LVN_GETDISPINFO: + hr = uiprivTableHandleLVN_GETDISPINFO(t, (NMLVDISPINFOW *) nmhdr, lResult); + if (hr != S_OK) { + // TODO + return FALSE; + } + return TRUE; + case NM_CUSTOMDRAW: + hr = uiprivTableHandleNM_CUSTOMDRAW(t, (NMLVCUSTOMDRAW *) nmhdr, lResult); + if (hr != S_OK) { + // TODO + return FALSE; + } + return TRUE; + case NM_CLICK: +#if 0 + { + NMITEMACTIVATE *nm = (NMITEMACTIVATE *) nmhdr; + LVHITTESTINFO ht; + WCHAR buf[256]; + + ZeroMemory(&ht, sizeof (LVHITTESTINFO)); + ht.pt = nm->ptAction; + if (SendMessageW(t->hwnd, LVM_SUBITEMHITTEST, 0, (LPARAM) (&ht)) == (LRESULT) (-1)) + MessageBoxW(GetAncestor(t->hwnd, GA_ROOT), L"No hit", L"No hit", MB_OK); + else { + wsprintf(buf, L"item %d subitem %d htflags 0x%I32X", + ht.iItem, ht.iSubItem, ht.flags); + MessageBoxW(GetAncestor(t->hwnd, GA_ROOT), buf, buf, MB_OK); + } + } + *lResult = 0; + return TRUE; +#else + hr = uiprivTableHandleNM_CLICK(t, (NMITEMACTIVATE *) nmhdr, lResult); + if (hr != S_OK) { + // TODO + return FALSE; + } + return TRUE; +#endif + case LVN_ITEMCHANGED: + { + NMLISTVIEW *nm = (NMLISTVIEW *) nmhdr; + UINT oldSelected, newSelected; + HRESULT hr; + + // TODO clean up these if cases + if (!t->inLButtonDown && t->edit == NULL) + return FALSE; + oldSelected = nm->uOldState & LVIS_SELECTED; + newSelected = nm->uNewState & LVIS_SELECTED; + if (t->inLButtonDown && oldSelected == 0 && newSelected != 0) { + t->inDoubleClickTimer = TRUE; + // TODO check error + SetTimer(t->hwnd, (UINT_PTR) (&(t->inDoubleClickTimer)), + GetDoubleClickTime(), NULL); + *lResult = 0; + return TRUE; + } + // the nm->iItem == -1 case is because that is used if "the change has been applied to all items in the list view" + if (t->edit != NULL && oldSelected != 0 && newSelected == 0 && (t->editedItem == nm->iItem || nm->iItem == -1)) { + // TODO see if the real list view accepts or rejects changes here; Windows Explorer accepts + hr = uiprivTableFinishEditingText(t); + if (hr != S_OK) { + // TODO + return FALSE; + } + *lResult = 0; + return TRUE; + } + return FALSE; + } + // the real list view accepts changes when scrolling or clicking column headers + case LVN_BEGINSCROLL: + case LVN_COLUMNCLICK: + hr = uiprivTableFinishEditingText(t); + if (hr != S_OK) { + // TODO + return FALSE; + } + *lResult = 0; + return TRUE; + } + return FALSE; +} + +static void uiTableDestroy(uiControl *c) +{ + uiTable *t = uiTable(c); + uiTableModel *model = t->model; + std::vector::iterator it; + HRESULT hr; + + hr = uiprivTableAbortEditingText(t); + if (hr != S_OK) { + // TODO + } + uiWindowsUnregisterWM_NOTIFYHandler(t->hwnd); + uiWindowsEnsureDestroyWindow(t->hwnd); + // detach table from model + for (it = model->tables->begin(); it != model->tables->end(); it++) { + if (*it == t) { + model->tables->erase(it); + break; + } + } + // free the columns + for (auto col : *(t->columns)) + uiprivFree(col); + delete t->columns; + // t->imagelist will be automatically destroyed + delete t->indeterminatePositions; + uiFreeControl(uiControl(t)); +} + +uiWindowsControlAllDefaultsExceptDestroy(uiTable) + +// suggested listview sizing from http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing: +// "columns widths that avoid truncated data x an integral number of items" +// Don't think that'll cut it when some cells have overlong data (eg +// stupidly long URLs). So for now, just hardcode a minimum. +// TODO Investigate using LVM_GETHEADER/HDM_LAYOUT here +// TODO investigate using LVM_APPROXIMATEVIEWRECT here +#define tableMinWidth 107 /* in line with other controls */ +#define tableMinHeight (14 * 3) /* header + 2 lines (roughly) */ + +static void uiTableMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + uiTable *t = uiTable(c); + uiWindowsSizing sizing; + int x, y; + + x = tableMinWidth; + y = tableMinHeight; + uiWindowsGetSizing(t->hwnd, &sizing); + uiWindowsSizingDlgUnitsToPixels(&sizing, &x, &y); + *width = x; + *height = y; +} + +static uiprivTableColumnParams *appendColumn(uiTable *t, const char *name, int colfmt) +{ + WCHAR *wstr; + LVCOLUMNW lvc; + uiprivTableColumnParams *p; + + ZeroMemory(&lvc, sizeof (LVCOLUMNW)); + lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT; + lvc.fmt = colfmt; + lvc.cx = 120; // TODO + wstr = toUTF16(name); + lvc.pszText = wstr; + if (SendMessageW(t->hwnd, LVM_INSERTCOLUMNW, t->nColumns, (LPARAM) (&lvc)) == (LRESULT) (-1)) + logLastError(L"error calling LVM_INSERTCOLUMNW in appendColumn()"); + uiprivFree(wstr); + t->nColumns++; + + p = uiprivNew(uiprivTableColumnParams); + p->textModelColumn = -1; + p->textEditableModelColumn = -1; + p->textParams = uiprivDefaultTextColumnOptionalParams; + p->imageModelColumn = -1; + p->checkboxModelColumn = -1; + p->checkboxEditableModelColumn = -1; + p->progressBarModelColumn = -1; + p->buttonModelColumn = -1; + t->columns->push_back(p); + return p; +} + +void uiTableAppendTextColumn(uiTable *t, const char *name, int textModelColumn, int textEditableModelColumn, uiTableTextColumnOptionalParams *textParams) +{ + uiprivTableColumnParams *p; + + p = appendColumn(t, name, LVCFMT_LEFT); + p->textModelColumn = textModelColumn; + p->textEditableModelColumn = textEditableModelColumn; + if (textParams != NULL) + p->textParams = *textParams; +} + +void uiTableAppendImageColumn(uiTable *t, const char *name, int imageModelColumn) +{ + uiprivTableColumnParams *p; + + p = appendColumn(t, name, LVCFMT_LEFT); + p->imageModelColumn = imageModelColumn; +} + +void uiTableAppendImageTextColumn(uiTable *t, const char *name, int imageModelColumn, int textModelColumn, int textEditableModelColumn, uiTableTextColumnOptionalParams *textParams) +{ + uiprivTableColumnParams *p; + + p = appendColumn(t, name, LVCFMT_LEFT); + p->textModelColumn = textModelColumn; + p->textEditableModelColumn = textEditableModelColumn; + if (textParams != NULL) + p->textParams = *textParams; + p->imageModelColumn = imageModelColumn; +} + +void uiTableAppendCheckboxColumn(uiTable *t, const char *name, int checkboxModelColumn, int checkboxEditableModelColumn) +{ + uiprivTableColumnParams *p; + + p = appendColumn(t, name, LVCFMT_LEFT); + p->checkboxModelColumn = checkboxModelColumn; + p->checkboxEditableModelColumn = checkboxEditableModelColumn; +} + +void uiTableAppendCheckboxTextColumn(uiTable *t, const char *name, int checkboxModelColumn, int checkboxEditableModelColumn, int textModelColumn, int textEditableModelColumn, uiTableTextColumnOptionalParams *textParams) +{ + uiprivTableColumnParams *p; + + p = appendColumn(t, name, LVCFMT_LEFT); + p->textModelColumn = textModelColumn; + p->textEditableModelColumn = textEditableModelColumn; + if (textParams != NULL) + p->textParams = *textParams; + p->checkboxModelColumn = checkboxModelColumn; + p->checkboxEditableModelColumn = checkboxEditableModelColumn; +} + +void uiTableAppendProgressBarColumn(uiTable *t, const char *name, int progressModelColumn) +{ + uiprivTableColumnParams *p; + + p = appendColumn(t, name, LVCFMT_LEFT); + p->progressBarModelColumn = progressModelColumn; +} + +void uiTableAppendButtonColumn(uiTable *t, const char *name, int buttonModelColumn, int buttonClickableModelColumn) +{ + uiprivTableColumnParams *p; + + // TODO see if we can get rid of this parameter + p = appendColumn(t, name, LVCFMT_LEFT); + p->buttonModelColumn = buttonModelColumn; + p->buttonClickableModelColumn = buttonClickableModelColumn; +} + +uiTable *uiNewTable(uiTableParams *p) +{ + uiTable *t; + int n; + HRESULT hr; + + uiWindowsNewControl(uiTable, t); + + t->columns = new std::vector; + t->model = p->Model; + t->backgroundColumn = p->RowBackgroundColorModelColumn; + + // WS_CLIPCHILDREN is here to prevent drawing over the edit box used for editing text + t->hwnd = uiWindowsEnsureCreateControlHWND(WS_EX_CLIENTEDGE, + WC_LISTVIEW, L"", + LVS_REPORT | LVS_OWNERDATA | LVS_SINGLESEL | WS_CLIPCHILDREN | WS_TABSTOP | WS_HSCROLL | WS_VSCROLL, + hInstance, NULL, + TRUE); + t->model->tables->push_back(t); + uiWindowsRegisterWM_NOTIFYHandler(t->hwnd, onWM_NOTIFY, uiControl(t)); + + // TODO: try LVS_EX_AUTOSIZECOLUMNS + // TODO check error + SendMessageW(t->hwnd, LVM_SETEXTENDEDLISTVIEWSTYLE, + (WPARAM) (LVS_EX_FULLROWSELECT | LVS_EX_LABELTIP | LVS_EX_SUBITEMIMAGES), + (LPARAM) (LVS_EX_FULLROWSELECT | LVS_EX_LABELTIP | LVS_EX_SUBITEMIMAGES)); + n = uiprivTableModelNumRows(t->model); + if (SendMessageW(t->hwnd, LVM_SETITEMCOUNT, (WPARAM) n, 0) == 0) + logLastError(L"error calling LVM_SETITEMCOUNT in uiNewTable()"); + + hr = uiprivUpdateImageListSize(t); + if (hr != S_OK) { + // TODO + } + + t->indeterminatePositions = new std::map, LONG>; + if (SetWindowSubclass(t->hwnd, tableSubProc, 0, (DWORD_PTR) t) == FALSE) + logLastError(L"SetWindowSubclass()"); + + return t; +} diff --git a/dep/libui/windows/table.hpp b/dep/libui/windows/table.hpp new file mode 100644 index 0000000..71946d6 --- /dev/null +++ b/dep/libui/windows/table.hpp @@ -0,0 +1,81 @@ +// 10 june 2018 +#include "../common/table.h" + +// table.cpp +#define uiprivNumLVN_GETDISPINFOSkip 3 +struct uiTableModel { + uiTableModelHandler *mh; + std::vector *tables; +}; +typedef struct uiprivTableColumnParams uiprivTableColumnParams; +struct uiprivTableColumnParams { + int textModelColumn; + int textEditableModelColumn; + uiTableTextColumnOptionalParams textParams; + + int imageModelColumn; + + int checkboxModelColumn; + int checkboxEditableModelColumn; + + int progressBarModelColumn; + + int buttonModelColumn; + int buttonClickableModelColumn; +}; +struct uiTable { + uiWindowsControl c; + uiTableModel *model; + HWND hwnd; + std::vector *columns; + WPARAM nColumns; + int backgroundColumn; + // TODO make sure replacing images while selected in the listview is even allowed + HIMAGELIST imagelist; + // TODO document all this + std::map, LONG> *indeterminatePositions; + BOOL inLButtonDown; + // TODO is this even necessary? it seems NM_CLICK is not sent if NM_DBLCLICK or LVN_ITEMACTIVATE (one of the two) happens... + BOOL inDoubleClickTimer; + HWND edit; + int editedItem; + int editedSubitem; +}; +extern int uiprivTableProgress(uiTable *t, int item, int subitem, int modelColumn, LONG *pos); + +// tabledispinfo.cpp +extern HRESULT uiprivTableHandleLVN_GETDISPINFO(uiTable *t, NMLVDISPINFOW *nm, LRESULT *lResult); + +// tabledraw.cpp +extern HRESULT uiprivTableHandleNM_CUSTOMDRAW(uiTable *t, NMLVCUSTOMDRAW *nm, LRESULT *lResult); +extern HRESULT uiprivUpdateImageListSize(uiTable *t); + +// tableediting.cpp +extern HRESULT uiprivTableResizeWhileEditing(uiTable *t); +extern HRESULT uiprivTableHandleNM_CLICK(uiTable *t, NMITEMACTIVATE *nm, LRESULT *lResult); +extern HRESULT uiprivTableFinishEditingText(uiTable *t); +extern HRESULT uiprivTableAbortEditingText(uiTable *t); + +// tablemetrics.cpp +typedef struct uiprivTableMetrics uiprivTableMetrics; +struct uiprivTableMetrics { + BOOL hasText; + BOOL hasImage; + BOOL focused; + BOOL selected; + + RECT itemBounds; + RECT itemIcon; + RECT itemLabel; + RECT subitemBounds; + RECT subitemIcon; + RECT subitemLabel; + + LRESULT bitmapMargin; + int cxIcon; + int cyIcon; + + RECT realTextBackground; + RECT realTextRect; +}; +extern HRESULT uiprivTableGetMetrics(uiTable *t, int iItem, int iSubItem, uiprivTableMetrics **mout); diff --git a/dep/libui/windows/tabledispinfo.cpp b/dep/libui/windows/tabledispinfo.cpp new file mode 100644 index 0000000..4198a1a --- /dev/null +++ b/dep/libui/windows/tabledispinfo.cpp @@ -0,0 +1,99 @@ +// 13 june 2018 +#include "uipriv_windows.hpp" +#include "table.hpp" + +// further reading: +// - https://msdn.microsoft.com/en-us/library/ye4z8x58.aspx + +static HRESULT handleLVIF_TEXT(uiTable *t, NMLVDISPINFOW *nm, uiprivTableColumnParams *p) +{ + int strcol; + uiTableValue *value; + WCHAR *wstr; + int progress; + HRESULT hr; + + if ((nm->item.mask & LVIF_TEXT) == 0) + return S_OK; + + strcol = -1; + if (p->textModelColumn != -1) + strcol = p->textModelColumn; + else if (p->buttonModelColumn != -1) + strcol = p->buttonModelColumn; + if (strcol != -1) { + value = uiprivTableModelCellValue(t->model, nm->item.iItem, strcol); + wstr = toUTF16(uiTableValueString(value)); + uiFreeTableValue(value); + // We *could* just make pszText into a freshly allocated + // conversion and avoid the limitation of cchTextMax. + // But then, we would have to keep things around for some + // amount of time (some pages on MSDN say 2 additional + // LVN_GETDISPINFO messages). And in practice, anything + // that results in extra LVN_GETDISPINFO messages (such + // as LVN_GETITEMRECT with LVIR_LABEL) will break this + // counting. + // TODO make it so we don't have to make a copy; instead we can convert directly into pszText (this will also avoid the risk of having a dangling surrogate pair at the end) + wcsncpy(nm->item.pszText, wstr, nm->item.cchTextMax); + nm->item.pszText[nm->item.cchTextMax - 1] = L'\0'; + uiprivFree(wstr); + return S_OK; + } + + if (p->progressBarModelColumn != -1) { + progress = uiprivTableProgress(t, nm->item.iItem, nm->item.iSubItem, p->progressBarModelColumn, NULL); + + if (progress == -1) { + // TODO either localize this or replace it with something that's language-neutral + // TODO ensure null terminator + wcsncpy(nm->item.pszText, L"Indeterminate", nm->item.cchTextMax); + return S_OK; + } + // TODO ensure null terminator + _snwprintf(nm->item.pszText, nm->item.cchTextMax, L"%d%%", progress); + return S_OK; + } + + return S_OK; +} + +static HRESULT handleLVIF_IMAGE(uiTable *t, NMLVDISPINFOW *nm, uiprivTableColumnParams *p) +{ + uiTableValue *value; + HRESULT hr; + + if (nm->item.iSubItem == 0 && p->imageModelColumn == -1 && p->checkboxModelColumn == -1) { + // Having an image list always leaves space for an image + // on the main item :| + // Other places on the internet imply that you should be + // able to do this but that it shouldn't work, but it works + // perfectly (and pixel-perfectly too) for me, so... + nm->item.mask |= LVIF_INDENT; + nm->item.iIndent = -1; + } + if ((nm->item.mask & LVIF_IMAGE) == 0) + return S_OK; // nothing to do here + + // TODO see if the -1 part is correct + // TODO see if we should use state instead of images for checkbox value + nm->item.iImage = -1; + if (p->imageModelColumn != -1 || p->checkboxModelColumn != -1) + nm->item.iImage = 0; + return S_OK; +} + +HRESULT uiprivTableHandleLVN_GETDISPINFO(uiTable *t, NMLVDISPINFOW *nm, LRESULT *lResult) +{ + uiprivTableColumnParams *p; + HRESULT hr; + + p = (*(t->columns))[nm->item.iSubItem]; + hr = handleLVIF_TEXT(t, nm, p); + if (hr != S_OK) + return hr; + hr = handleLVIF_IMAGE(t, nm, p); + if (hr != S_OK) + return hr; + *lResult = 0; + return S_OK; +} diff --git a/dep/libui/windows/tabledraw.cpp b/dep/libui/windows/tabledraw.cpp new file mode 100644 index 0000000..eb50f28 --- /dev/null +++ b/dep/libui/windows/tabledraw.cpp @@ -0,0 +1,739 @@ +// 14 june 2018 +#include "uipriv_windows.hpp" +#include "table.hpp" + +// TODOs: +// - properly hide selection when not focused (or switch on LVS_SHOWSELALWAYS and draw that state) + +// TODO maybe split this into item and subitem structs? +struct drawState { + uiTable *t; + uiTableModel *model; + uiprivTableColumnParams *p; + + HDC dc; + int iItem; + int iSubItem; + + uiprivTableMetrics *m; + + COLORREF bgColor; + HBRUSH bgBrush; + BOOL freeBgBrush; + COLORREF textColor; + HBRUSH textBrush; + BOOL freeTextBrush; +}; + +static HRESULT drawBackgrounds(HRESULT hr, struct drawState *s) +{ + if (hr != S_OK) + return hr; + if (s->m->hasImage) + if (FillRect(s->dc, &(s->m->subitemIcon), GetSysColorBrush(COLOR_WINDOW)) == 0) { + logLastError(L"FillRect() icon"); + return E_FAIL; + } + if (FillRect(s->dc, &(s->m->realTextBackground), s->bgBrush) == 0) { + logLastError(L"FillRect()"); + return E_FAIL; + } + return S_OK; +} + +static void centerImageRect(RECT *image, RECT *space) +{ + LONG xoff, yoff; + + // first make sure both have the same upper-left + xoff = image->left - space->left; + yoff = image->top - space->top; + image->left -= xoff; + image->top -= yoff; + image->right -= xoff; + image->bottom -= yoff; + + // now center + xoff = ((space->right - space->left) - (image->right - image->left)) / 2; + yoff = ((space->bottom - space->top) - (image->bottom - image->top)) / 2; + image->left += xoff; + image->top += yoff; + image->right += xoff; + image->bottom += yoff; +} + +static HRESULT drawImagePart(HRESULT hr, struct drawState *s) +{ + uiTableValue *value; + IWICBitmap *wb; + HBITMAP b; + RECT r; + UINT fStyle; + + if (hr != S_OK) + return hr; + if (s->p->imageModelColumn == -1) + return S_OK; + + value = uiprivTableModelCellValue(s->model, s->iItem, s->p->imageModelColumn); + wb = uiprivImageAppropriateForDC(uiTableValueImage(value), s->dc); + uiFreeTableValue(value); + + hr = uiprivWICToGDI(wb, s->dc, s->m->cxIcon, s->m->cyIcon, &b); + if (hr != S_OK) + return hr; + // TODO rewrite this condition to make more sense; possibly swap the if and else blocks too + // TODO proper cleanup + if (ImageList_GetImageCount(s->t->imagelist) > 1) { + if (ImageList_Replace(s->t->imagelist, 0, b, NULL) == 0) { + logLastError(L"ImageList_Replace()"); + return E_FAIL; + } + } else + if (ImageList_Add(s->t->imagelist, b, NULL) == -1) { + logLastError(L"ImageList_Add()"); + return E_FAIL; + } + // TODO error check + DeleteObject(b); + + r = s->m->subitemIcon; + r.right = r.left + s->m->cxIcon; + r.bottom = r.top + s->m->cyIcon; + centerImageRect(&r, &(s->m->subitemIcon)); + fStyle = ILD_NORMAL; + if (s->m->selected) + fStyle = ILD_SELECTED; + if (ImageList_Draw(s->t->imagelist, 0, + s->dc, r.left, r.top, fStyle) == 0) { + logLastError(L"ImageList_Draw()"); + return E_FAIL; + } + return S_OK; +} + +// references for checkbox drawing: +// - https://blogs.msdn.microsoft.com/oldnewthing/20171129-00/?p=97485 +// - https://blogs.msdn.microsoft.com/oldnewthing/20171201-00/?p=97505 + +static HRESULT drawUnthemedCheckbox(struct drawState *s, int checked, int enabled) +{ + RECT r; + UINT state; + + r = s->m->subitemIcon; + // this is what the actual list view LVS_EX_CHECKBOXES code does to size the checkboxes + // TODO reverify the initial size + r.right = r.left + GetSystemMetrics(SM_CXSMICON); + r.bottom = r.top + GetSystemMetrics(SM_CYSMICON); + if (InflateRect(&r, -GetSystemMetrics(SM_CXEDGE), -GetSystemMetrics(SM_CYEDGE)) == 0) { + logLastError(L"InflateRect()"); + return E_FAIL; + } + r.right++; + r.bottom++; + + centerImageRect(&r, &(s->m->subitemIcon)); + state = DFCS_BUTTONCHECK | DFCS_FLAT; + if (checked) + state |= DFCS_CHECKED; + if (!enabled) + state |= DFCS_INACTIVE; + if (DrawFrameControl(s->dc, &r, DFC_BUTTON, state) == 0) { + logLastError(L"DrawFrameControl()"); + return E_FAIL; + } + return S_OK; +} + +static HRESULT drawThemedCheckbox(struct drawState *s, HTHEME theme, int checked, int enabled) +{ + RECT r; + SIZE size; + int state; + HRESULT hr; + + hr = GetThemePartSize(theme, s->dc, + BP_CHECKBOX, CBS_UNCHECKEDNORMAL, + NULL, TS_DRAW, &size); + if (hr != S_OK) { + logHRESULT(L"GetThemePartSize()", hr); + return hr; // TODO fall back? + } + r = s->m->subitemIcon; + r.right = r.left + size.cx; + r.bottom = r.top + size.cy; + + centerImageRect(&r, &(s->m->subitemIcon)); + if (!checked && enabled) + state = CBS_UNCHECKEDNORMAL; + else if (checked && enabled) + state = CBS_CHECKEDNORMAL; + else if (!checked && !enabled) + state = CBS_UNCHECKEDDISABLED; + else + state = CBS_CHECKEDDISABLED; + hr = DrawThemeBackground(theme, s->dc, + BP_CHECKBOX, state, + &r, NULL); + if (hr != S_OK) { + logHRESULT(L"DrawThemeBackground()", hr); + return hr; + } + return S_OK; +} + +static HRESULT drawCheckboxPart(HRESULT hr, struct drawState *s) +{ + uiTableValue *value; + int checked, enabled; + HTHEME theme; + + if (hr != S_OK) + return hr; + if (s->p->checkboxModelColumn == -1) + return S_OK; + + value = uiprivTableModelCellValue(s->model, s->iItem, s->p->checkboxModelColumn); + checked = uiTableValueInt(value); + uiFreeTableValue(value); + enabled = uiprivTableModelCellEditable(s->model, s->iItem, s->p->checkboxEditableModelColumn); + + theme = OpenThemeData(s->t->hwnd, L"button"); + if (theme != NULL) { + hr = drawThemedCheckbox(s, theme, checked, enabled); + if (hr != S_OK) + return hr; + hr = CloseThemeData(theme); + if (hr != S_OK) { + logHRESULT(L"CloseThemeData()", hr); + return hr; + } + } else { + hr = drawUnthemedCheckbox(s, checked, enabled); + if (hr != S_OK) + return hr; + } + return S_OK; +} + +static HRESULT drawTextPart(HRESULT hr, struct drawState *s) +{ + COLORREF prevText; + int prevMode; + RECT r; + uiTableValue *value; + WCHAR *wstr; + + if (hr != S_OK) + return hr; + if (!s->m->hasText) + return S_OK; + // don't draw the text underneath an edit control + if (s->t->edit != NULL && s->t->editedItem == s->iItem && s->t->editedSubitem == s->iSubItem) + return S_OK; + + prevText = SetTextColor(s->dc, s->textColor); + if (prevText == CLR_INVALID) { + logLastError(L"SetTextColor()"); + return E_FAIL; + } + prevMode = SetBkMode(s->dc, TRANSPARENT); + if (prevMode == 0) { + logLastError(L"SetBkMode()"); + return E_FAIL; + } + + value = uiprivTableModelCellValue(s->model, s->iItem, s->p->textModelColumn); + wstr = toUTF16(uiTableValueString(value)); + uiFreeTableValue(value); + // These flags are a menagerie of flags from various sources: + // guessing, the Windows 2000 source leak, various custom + // draw examples on the web, etc. + // TODO find the real correct flags + if (DrawTextW(s->dc, wstr, -1, &(s->m->realTextRect), DT_LEFT | DT_VCENTER | DT_END_ELLIPSIS | DT_SINGLELINE | DT_NOPREFIX | DT_EDITCONTROL) == 0) { + uiprivFree(wstr); + logLastError(L"DrawTextW()"); + return E_FAIL; + } + uiprivFree(wstr); + + // TODO decide once and for all what to compare to here and with SelectObject() + if (SetBkMode(s->dc, prevMode) != TRANSPARENT) { + logLastError(L"SetBkMode() prev"); + return E_FAIL; + } + if (SetTextColor(s->dc, prevText) != s->textColor) { + logLastError(L"SetTextColor() prev"); + return E_FAIL; + } + return S_OK; +} + +// much of this is to imitate what shell32.dll's CDrawProgressBar does +#define indeterminateSegments 8 + +static HRESULT drawProgressBarPart(HRESULT hr, struct drawState *s) +{ + int progress; + LONG indeterminatePos; + HTHEME theme; + RECT r; + RECT rBorder, rFill[2]; + int i, nFill; + TEXTMETRICW tm; + int sysColor; + + if (hr != S_OK) + return hr; + if (s->p->progressBarModelColumn == -1) + return S_OK; + + progress = uiprivTableProgress(s->t, s->iItem, s->iSubItem, s->p->progressBarModelColumn, &indeterminatePos); + + theme = OpenThemeData(s->t->hwnd, L"PROGRESS"); + + if (GetTextMetricsW(s->dc, &tm) == 0) { + logLastError(L"GetTextMetricsW()"); + hr = E_FAIL; + goto fail; + } + r = s->m->subitemBounds; + // this sets the height of the progressbar and vertically centers it in one fell swoop + r.top += (r.bottom - tm.tmHeight - r.top) / 2; + r.bottom = r.top + tm.tmHeight; + + // TODO check errors + rBorder = r; + InflateRect(&rBorder, -1, -1); + if (theme != NULL) { + RECT crect; + + hr = GetThemeBackgroundContentRect(theme, s->dc, + PP_TRANSPARENTBAR, PBBS_NORMAL, + &rBorder, &crect); + if (hr != S_OK) { + logHRESULT(L"GetThemeBackgroundContentRect()", hr); + goto fail; + } + hr = DrawThemeBackground(theme, s->dc, + PP_TRANSPARENTBAR, PBBS_NORMAL, + &crect, NULL); + if (hr != S_OK) { + logHRESULT(L"DrawThemeBackground() border", hr); + goto fail; + } + } else { + HPEN pen, prevPen; + HBRUSH brush, prevBrush; + + sysColor = COLOR_HIGHLIGHT; + if (s->m->selected) + sysColor = COLOR_HIGHLIGHTTEXT; + + // TODO check errors everywhere + pen = CreatePen(PS_SOLID, 1, GetSysColor(sysColor)); + prevPen = (HPEN) SelectObject(s->dc, pen); + brush = (HBRUSH) GetStockObject(NULL_BRUSH); + prevBrush = (HBRUSH) SelectObject(s->dc, brush); + Rectangle(s->dc, rBorder.left, rBorder.top, rBorder.right, rBorder.bottom); + SelectObject(s->dc, prevBrush); + SelectObject(s->dc, prevPen); + DeleteObject(pen); + } + + nFill = 1; + rFill[0] = r; + // TODO check error + InflateRect(&rFill[0], -1, -1); + if (progress != -1) + rFill[0].right -= (rFill[0].right - rFill[0].left) * (100 - progress) / 100; + else { + LONG barWidth; + LONG pieceWidth; + + // TODO explain all this + // TODO this should really start the progressbar scrolling into view instead of already on screen when first set + rFill[1] = rFill[0]; // save in case we need it + barWidth = rFill[0].right - rFill[0].left; + pieceWidth = barWidth / indeterminateSegments; + rFill[0].left += indeterminatePos % barWidth; + if ((rFill[0].left + pieceWidth) >= rFill[0].right) { + // make this piece wrap back around + nFill++; + rFill[1].right = rFill[1].left + (pieceWidth - (rFill[0].right - rFill[0].left)); + } else + rFill[0].right = rFill[0].left + pieceWidth; + } + for (i = 0; i < nFill; i++) + if (theme != NULL) { + hr = DrawThemeBackground(theme, s->dc, + PP_FILL, PBFS_NORMAL, + &rFill[i], NULL); + if (hr != S_OK) { + logHRESULT(L"DrawThemeBackground() fill", hr); + goto fail; + } + } else + // TODO check errors + FillRect(s->dc, &rFill[i], GetSysColorBrush(sysColor)); + + hr = S_OK; +fail: + // TODO check errors + if (theme != NULL) + CloseThemeData(theme); + return hr; +} + +static HRESULT drawButtonPart(HRESULT hr, struct drawState *s) +{ + uiTableValue *value; + WCHAR *wstr; + bool enabled; + HTHEME theme; + RECT r; + TEXTMETRICW tm; + + if (hr != S_OK) + return hr; + if (s->p->buttonModelColumn == -1) + return S_OK; + + value = uiprivTableModelCellValue(s->model, s->iItem, s->p->buttonModelColumn); + wstr = toUTF16(uiTableValueString(value)); + uiFreeTableValue(value); + enabled = uiprivTableModelCellEditable(s->model, s->iItem, s->p->buttonClickableModelColumn); + + theme = OpenThemeData(s->t->hwnd, L"button"); + + if (GetTextMetricsW(s->dc, &tm) == 0) { + logLastError(L"GetTextMetricsW()"); + hr = E_FAIL; + goto fail; + } + r = s->m->subitemBounds; + + if (theme != NULL) { + int state; + + state = PBS_NORMAL; + if (!enabled) + state = PBS_DISABLED; + hr = DrawThemeBackground(theme, s->dc, + BP_PUSHBUTTON, state, + &r, NULL); + if (hr != S_OK) { + logHRESULT(L"DrawThemeBackground()", hr); + goto fail; + } + // TODO DT_EDITCONTROL? + // TODO DT_PATH_ELLIPSIS DT_WORD_ELLIPSIS instead of DT_END_ELLIPSIS? a middle-ellipsis option would be ideal here + // TODO is there a theme property we can get instead of hardcoding these flags? if not, make these flags a macro + hr = DrawThemeText(theme, s->dc, + BP_PUSHBUTTON, state, + wstr, -1, + DT_CENTER | DT_VCENTER | DT_END_ELLIPSIS | DT_SINGLELINE | DT_NOPREFIX, 0, + &r); + if (hr != S_OK) { + logHRESULT(L"DrawThemeText()", hr); + goto fail; + } + } else { + UINT state; + HBRUSH color, prevColor; + int prevBkMode; + + // TODO check errors + // TODO explain why we're not doing this in the themed case (it has to do with extra transparent pixels) + InflateRect(&r, -1, -1); + state = DFCS_BUTTONPUSH; + if (!enabled) + state |= DFCS_INACTIVE; + if (DrawFrameControl(s->dc, &r, DFC_BUTTON, state) == 0) { + logLastError(L"DrawFrameControl()"); + hr = E_FAIL; + goto fail; + } + color = GetSysColorBrush(COLOR_BTNTEXT); + // TODO check errors for these two + prevColor = (HBRUSH) SelectObject(s->dc, color); + prevBkMode = SetBkMode(s->dc, TRANSPARENT); + // TODO DT_EDITCONTROL? + // TODO DT_PATH_ELLIPSIS DT_WORD_ELLIPSIS instead of DT_END_ELLIPSIS? a middle-ellipsis option would be ideal here + if (DrawTextW(s->dc, wstr, -1, &r, DT_CENTER | DT_VCENTER | DT_END_ELLIPSIS | DT_SINGLELINE | DT_NOPREFIX) == 0) { + logLastError(L"DrawTextW()"); + hr = E_FAIL; + goto fail; + } + // TODO check errors for these two + SetBkMode(s->dc, prevBkMode); + SelectObject(s->dc, prevColor); + } + + hr = S_OK; +fail: + // TODO check errors + if (theme != NULL) + CloseThemeData(theme); + uiprivFree(wstr); + return hr; +} + +static HRESULT freeDrawState(struct drawState *s) +{ + HRESULT hr, hrret; + + hrret = S_OK; + if (s->m != NULL) { + uiprivFree(s->m); + s->m = NULL; + } + if (s->freeTextBrush) { + if (DeleteObject(s->textBrush) == 0) { + logLastError(L"DeleteObject()"); + hrret = E_FAIL; + // continue cleaning up anyway + } + s->freeTextBrush = FALSE; + } + if (s->freeBgBrush) { + if (DeleteObject(s->bgBrush) == 0) { + logLastError(L"DeleteObject()"); + hrret = E_FAIL; + // continue cleaning up anyway + } + s->freeBgBrush = FALSE; + } + return hrret; +} + +static COLORREF blend(COLORREF base, double r, double g, double b, double a) +{ + double br, bg, bb; + + br = ((double) GetRValue(base)) / 255.0; + bg = ((double) GetGValue(base)) / 255.0; + bb = ((double) GetBValue(base)) / 255.0; + + br = (r * a) + (br * (1.0 - a)); + bg = (g * a) + (bg * (1.0 - a)); + bb = (b * a) + (bb * (1.0 - a)); + return RGB((BYTE) (br * 255), + (BYTE) (bg * 255), + (BYTE) (bb * 255)); +} + +static HRESULT fillDrawState(struct drawState *s, uiTable *t, NMLVCUSTOMDRAW *nm, uiprivTableColumnParams *p) +{ + LRESULT state; + HWND header; + HRESULT hr; + + ZeroMemory(s, sizeof (struct drawState)); + s->t = t; + s->model = t->model; + s->p = p; + + s->dc = nm->nmcd.hdc; + s->iItem = nm->nmcd.dwItemSpec; + s->iSubItem = nm->iSubItem; + + hr = uiprivTableGetMetrics(t, s->iItem, s->iSubItem, &(s->m)); + if (hr != S_OK) + goto fail; + + if (s->m->selected) { + s->bgColor = GetSysColor(COLOR_HIGHLIGHT); + s->bgBrush = GetSysColorBrush(COLOR_HIGHLIGHT); + s->textColor = GetSysColor(COLOR_HIGHLIGHTTEXT); + s->textBrush = GetSysColorBrush(COLOR_HIGHLIGHTTEXT); + } else { + double r, g, b, a; + + s->bgColor = GetSysColor(COLOR_WINDOW); + s->bgBrush = GetSysColorBrush(COLOR_WINDOW); + if (uiprivTableModelColorIfProvided(s->model, s->iItem, t->backgroundColumn, &r, &g, &b, &a)) { + s->bgColor = blend(s->bgColor, r, g, b, a); + s->bgBrush = CreateSolidBrush(s->bgColor); + if (s->bgBrush == NULL) { + logLastError(L"CreateSolidBrush()"); + hr = E_FAIL; + goto fail; + } + s->freeBgBrush = TRUE; + } + s->textColor = GetSysColor(COLOR_WINDOWTEXT); + s->textBrush = GetSysColorBrush(COLOR_WINDOWTEXT); + if (uiprivTableModelColorIfProvided(s->model, s->iItem, p->textParams.ColorModelColumn, &r, &g, &b, &a)) { + s->textColor = blend(s->bgColor, r, g, b, a); + s->textBrush = CreateSolidBrush(s->textColor); + if (s->textBrush == NULL) { + logLastError(L"CreateSolidBrush()"); + hr = E_FAIL; + goto fail; + } + s->freeTextBrush = TRUE; + } + } + + return S_OK; +fail: + // ignore the error; we need to return the one we got above + freeDrawState(s); + return hr; +} + +static HRESULT updateAndDrawFocusRects(HRESULT hr, uiTable *t, HDC dc, int iItem, RECT *realTextBackground, RECT *focus, bool *first) +{ + LRESULT state; + + if (hr != S_OK) + return hr; + if (GetFocus() != t->hwnd) + return S_OK; + // uItemState CDIS_FOCUS doesn't quite work right because of bugs in the Windows list view that causes spurious redraws without the flag while we hover over the focused item + // TODO only call this once + state = SendMessageW(t->hwnd, LVM_GETITEMSTATE, (WPARAM) iItem, (LRESULT) (LVIS_FOCUSED)); + if ((state & LVIS_FOCUSED) == 0) + return S_OK; + + if (realTextBackground != NULL) + if (*first) { + *focus = *realTextBackground; + *first = false; + return S_OK; + } else if (focus->right == realTextBackground->left) { + focus->right = realTextBackground->right; + return S_OK; + } + if (DrawFocusRect(dc, focus) == 0) { + logLastError(L"DrawFocusRect()"); + return E_FAIL; + } + if (realTextBackground != NULL) + *focus = *realTextBackground; + return S_OK; +} + +// normally we would only draw stuff in subitem stages +// this broke when we tried drawing focus rects in postpaint; the drawing either kept getting wiped or overdrawn, mouse hovering had something to do with it, and none of the "solutions" to this or similar problems on the internet worked +// so now we do everything in the item prepaint stage +// TODO consider switching to full-on owner draw +// TODO only compute the background brushes once? +HRESULT uiprivTableHandleNM_CUSTOMDRAW(uiTable *t, NMLVCUSTOMDRAW *nm, LRESULT *lResult) +{ + struct drawState s; + uiprivTableColumnParams *p; + NMLVCUSTOMDRAW b; + size_t i, n; + RECT focus; + bool focusFirst; + HRESULT hr; + + switch (nm->nmcd.dwDrawStage) { + case CDDS_PREPAINT: + *lResult = CDRF_NOTIFYITEMDRAW; + return S_OK; + case CDDS_ITEMPREPAINT: + break; + default: + *lResult = CDRF_DODEFAULT; + return S_OK; + } + + n = t->columns->size(); + b = *nm; + focusFirst = true; + for (i = 0; i < n; i++) { + b.iSubItem = i; + p = (*(t->columns))[i]; + hr = fillDrawState(&s, t, &b, p); + if (hr != S_OK) + return hr; + hr = drawBackgrounds(S_OK, &s); + hr = drawImagePart(hr, &s); + hr = drawCheckboxPart(hr, &s); + hr = drawTextPart(hr, &s); + hr = drawProgressBarPart(hr, &s); + hr = drawButtonPart(hr, &s); + hr = updateAndDrawFocusRects(hr, s.t, s.dc, nm->nmcd.dwItemSpec, &(s.m->realTextBackground), &focus, &focusFirst); + if (hr != S_OK) + goto fail; + hr = freeDrawState(&s); + if (hr != S_OK) // TODO really error out here? + return hr; + } + // and draw the last focus rect + hr = updateAndDrawFocusRects(hr, t, nm->nmcd.hdc, nm->nmcd.dwItemSpec, NULL, &focus, &focusFirst); + if (hr != S_OK) + return hr; + *lResult = CDRF_SKIPDEFAULT; + return S_OK; +fail: + // ignore error here + // TODO this is awkward cleanup placement for something that only really exists in a for loop + freeDrawState(&s); + return hr; +} + +// TODO run again when the DPI or the theme changes +// TODO properly clean things up here +// TODO properly destroy the old lists here too +HRESULT uiprivUpdateImageListSize(uiTable *t) +{ + HDC dc; + int cxList, cyList; + HTHEME theme; + SIZE sizeCheck; + HRESULT hr; + + dc = GetDC(t->hwnd); + if (dc == NULL) { + logLastError(L"GetDC()"); + return E_FAIL; + } + + cxList = GetSystemMetrics(SM_CXSMICON); + cyList = GetSystemMetrics(SM_CYSMICON); + sizeCheck.cx = cxList; + sizeCheck.cy = cyList; + theme = OpenThemeData(t->hwnd, L"button"); + if (theme != NULL) { + hr = GetThemePartSize(theme, dc, + BP_CHECKBOX, CBS_UNCHECKEDNORMAL, + NULL, TS_DRAW, &sizeCheck); + if (hr != S_OK) { + logHRESULT(L"GetThemePartSize()", hr); + return hr; // TODO fall back? + } + // make sure these checkmarks fit + // unthemed checkmarks will by the code above be smaller than cxList/cyList here + if (cxList < sizeCheck.cx) + cxList = sizeCheck.cx; + if (cyList < sizeCheck.cy) + cyList = sizeCheck.cy; + hr = CloseThemeData(theme); + if (hr != S_OK) { + logHRESULT(L"CloseThemeData()", hr); + return hr; + } + } + + // TODO handle errors + t->imagelist = ImageList_Create(cxList, cyList, + ILC_COLOR32, + 1, 1); + if (t->imagelist == NULL) { + logLastError(L"ImageList_Create()"); + return E_FAIL; + } + // TODO will this return NULL here because it's an initial state? + SendMessageW(t->hwnd, LVM_SETIMAGELIST, LVSIL_SMALL, (LPARAM) (t->imagelist)); + + if (ReleaseDC(t->hwnd, dc) == 0) { + logLastError(L"ReleaseDC()"); + return E_FAIL; + } + return S_OK; +} diff --git a/dep/libui/windows/tableediting.cpp b/dep/libui/windows/tableediting.cpp new file mode 100644 index 0000000..7bbb450 --- /dev/null +++ b/dep/libui/windows/tableediting.cpp @@ -0,0 +1,262 @@ +// 17 june 2018 +#include "uipriv_windows.hpp" +#include "table.hpp" + +// TODOs +// - clicking on the same item restarts editing instead of cancels it + +// this is not how the real list view positions and sizes the edit control, but this is a) close enough b) a lot easier to follow c) something I can actually get working d) something I'm slightly more comfortable including in libui +static HRESULT resizeEdit(uiTable *t, WCHAR *wstr, int iItem, int iSubItem) +{ + uiprivTableMetrics *m; + RECT r; + HDC dc; + HFONT prevFont; + TEXTMETRICW tm; + SIZE textSize; + RECT editRect, clientRect; + HRESULT hr; + + hr = uiprivTableGetMetrics(t, iItem, iSubItem, &m); + if (hr != S_OK) + return hr; + r = m->realTextRect; + uiprivFree(m); + + // TODO check errors for all these + dc = GetDC(t->hwnd); // use the list view DC since we're using its coordinate space + prevFont = (HFONT) SelectObject(dc, hMessageFont); + GetTextMetricsW(dc, &tm); + GetTextExtentPoint32W(dc, wstr, wcslen(wstr), &textSize); + SelectObject(dc, prevFont); + ReleaseDC(t->hwnd, dc); + + SendMessageW(t->edit, EM_GETRECT, 0, (LPARAM) (&editRect)); + r.left -= editRect.left; + // find the top of the text + r.top += ((r.bottom - r.top) - tm.tmHeight) / 2; + // and move THAT by the right offset + r.top -= editRect.top; + r.right = r.left + textSize.cx; + // the real listview does this to add some extra space at the end + // TODO this still isn't enough space + r.right += 4 * GetSystemMetrics(SM_CXEDGE) + GetSystemMetrics(SM_CYEDGE); + // and make the bottom equally positioned to the top + r.bottom = r.top + editRect.top + tm.tmHeight + editRect.top; + + // make sure the edit box doesn't stretch outside the listview + // the list view just does this, which is dumb for when the list view wouldn't be visible at all, but given that it doesn't scroll the edit into view either... + // TODO check errors + GetClientRect(t->hwnd, &clientRect); + IntersectRect(&r, &r, &clientRect); + + // TODO check error or use the right function + SetWindowPos(t->edit, NULL, + r.left, r.top, + r.right - r.left, r.bottom - r.top, + SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER); + return S_OK; +} + +// the real list view intercepts these keys to control editing +static LRESULT CALLBACK editSubProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIDSubclass, DWORD_PTR dwRefData) +{ + uiTable *t = (uiTable *) dwRefData; + HRESULT hr; + + switch (uMsg) { + case WM_KEYDOWN: + switch (wParam) { + // TODO handle VK_TAB and VK_SHIFT+VK_TAB + case VK_RETURN: + hr = uiprivTableFinishEditingText(t); + if (hr != S_OK) { + // TODO + } + return 0; // yes, the real list view just returns here + case VK_ESCAPE: + hr = uiprivTableAbortEditingText(t); + if (hr != S_OK) { + // TODO + } + return 0; + } + break; + // the real list view also forces these flags + case WM_GETDLGCODE: + return DLGC_HASSETSEL | DLGC_WANTALLKEYS; + case WM_NCDESTROY: + if (RemoveWindowSubclass(hwnd, editSubProc, uIDSubclass) == FALSE) + logLastError(L"RemoveWindowSubclass()"); + // fall through + } + return DefSubclassProc(hwnd, uMsg, wParam, lParam); +} + +static HRESULT openEditControl(uiTable *t, int iItem, int iSubItem, uiprivTableColumnParams *p) +{ + uiTableValue *value; + WCHAR *wstr; + HRESULT hr; + + // the real list view accepts changes to the existing item when editing a new item + hr = uiprivTableFinishEditingText(t); + if (hr != S_OK) + return hr; + + // the real list view creates the edit control with the string + value = uiprivTableModelCellValue(t->model, iItem, p->textModelColumn); + wstr = toUTF16(uiTableValueString(value)); + uiFreeTableValue(value); + // TODO copy WS_EX_RTLREADING + t->edit = CreateWindowExW(0, + L"EDIT", wstr, + // these styles are what the normal listview edit uses + WS_CHILD | WS_CLIPSIBLINGS | WS_BORDER | ES_AUTOHSCROLL, + // as is this size + 0, 0, 16384, 16384, + // and this control ID + t->hwnd, (HMENU) 1, hInstance, NULL); + if (t->edit == NULL) { + logLastError(L"CreateWindowExW()"); + uiprivFree(wstr); + return E_FAIL; + } + SendMessageW(t->edit, WM_SETFONT, (WPARAM) hMessageFont, (LPARAM) TRUE); + // TODO check errors + SetWindowSubclass(t->edit, editSubProc, 0, (DWORD_PTR) t); + + hr = resizeEdit(t, wstr, iItem, iSubItem); + if (hr != S_OK) + // TODO proper cleanup + return hr; + // TODO check errors on these two, if any + SetFocus(t->edit); + ShowWindow(t->edit, SW_SHOW); + SendMessageW(t->edit, EM_SETSEL, 0, (LPARAM) (-1)); + + uiprivFree(wstr); + t->editedItem = iItem; + t->editedSubitem = iSubItem; + return S_OK; +} + +HRESULT uiprivTableResizeWhileEditing(uiTable *t) +{ + WCHAR *text; + HRESULT hr; + + if (t->edit == NULL) + return S_OK; + text = windowText(t->edit); + hr = resizeEdit(t, text, t->editedItem, t->editedSubitem); + uiprivFree(text); + return hr; +} + +HRESULT uiprivTableFinishEditingText(uiTable *t) +{ + uiprivTableColumnParams *p; + uiTableValue *value; + char *text; + + if (t->edit == NULL) + return S_OK; + text = uiWindowsWindowText(t->edit); + value = uiNewTableValueString(text); + uiFreeText(text); + p = (*(t->columns))[t->editedSubitem]; + uiprivTableModelSetCellValue(t->model, t->editedItem, p->textModelColumn, value); + uiFreeTableValue(value); + // always refresh the value in case the model rejected it + if (SendMessageW(t->hwnd, LVM_UPDATE, (WPARAM) (t->editedItem), 0) == (LRESULT) (-1)) { + logLastError(L"LVM_UPDATE"); + return E_FAIL; + } + return uiprivTableAbortEditingText(t); +} + +HRESULT uiprivTableAbortEditingText(uiTable *t) +{ + HWND edit; + + if (t->edit == NULL) + return S_OK; + // set t->edit to NULL now so we don't trigger commits on focus killed + edit = t->edit; + t->edit = NULL; + + if (DestroyWindow(edit) == 0) { + logLastError(L"DestroyWindow()"); + return E_FAIL; + } + return S_OK; +} + +HRESULT uiprivTableHandleNM_CLICK(uiTable *t, NMITEMACTIVATE *nm, LRESULT *lResult) +{ + LVHITTESTINFO ht; + uiprivTableColumnParams *p; + int modelColumn, editableColumn; + bool text, checkbox; + uiTableValue *value; + int checked, editable; + HRESULT hr; + + ZeroMemory(&ht, sizeof (LVHITTESTINFO)); + ht.pt = nm->ptAction; + if (SendMessageW(t->hwnd, LVM_SUBITEMHITTEST, 0, (LPARAM) (&ht)) == (LRESULT) (-1)) + goto done; + + modelColumn = -1; + editableColumn = -1; + text = false; + checkbox = false; + p = (*(t->columns))[ht.iSubItem]; + if (p->textModelColumn != -1) { + modelColumn = p->textModelColumn; + editableColumn = p->textEditableModelColumn; + text = true; + } else if (p->checkboxModelColumn != -1) { + modelColumn = p->checkboxModelColumn; + editableColumn = p->checkboxEditableModelColumn; + checkbox = true; + } else if (p->buttonModelColumn != -1) { + modelColumn = p->buttonModelColumn; + editableColumn = p->buttonClickableModelColumn; + } + if (modelColumn == -1) + goto done; + + if (text && t->inDoubleClickTimer) + // don't even ask for info if it's too soon to edit text + goto done; + + if (!uiprivTableModelCellEditable(t->model, ht.iItem, editableColumn)) + goto done; + + if (text) { + hr = openEditControl(t, ht.iItem, ht.iSubItem, p); + if (hr != S_OK) + return hr; + } else if (checkbox) { + if ((ht.flags & LVHT_ONITEMICON) == 0) + goto done; + value = uiprivTableModelCellValue(t->model, ht.iItem, modelColumn); + checked = uiTableValueInt(value); + uiFreeTableValue(value); + value = uiNewTableValueInt(!checked); + uiprivTableModelSetCellValue(t->model, ht.iItem, modelColumn, value); + uiFreeTableValue(value); + } else + uiprivTableModelSetCellValue(t->model, ht.iItem, modelColumn, NULL); + // always refresh the value in case the model rejected it + if (SendMessageW(t->hwnd, LVM_UPDATE, (WPARAM) (ht.iItem), 0) == (LRESULT) (-1)) { + logLastError(L"LVM_UPDATE"); + return E_FAIL; + } + +done: + *lResult = 0; + return S_OK; +} diff --git a/dep/libui/windows/tablemetrics.cpp b/dep/libui/windows/tablemetrics.cpp new file mode 100644 index 0000000..64236b9 --- /dev/null +++ b/dep/libui/windows/tablemetrics.cpp @@ -0,0 +1,105 @@ +// 14 june 2018 +#include "uipriv_windows.hpp" +#include "table.hpp" + +static HRESULT itemRect(HRESULT hr, uiTable *t, UINT uMsg, WPARAM wParam, LONG left, LONG top, LRESULT bad, RECT *r) +{ + if (hr != S_OK) + return hr; + ZeroMemory(r, sizeof (RECT)); + r->left = left; + r->top = top; + if (SendMessageW(t->hwnd, uMsg, wParam, (LPARAM) r) == bad) { + logLastError(L"itemRect() message"); + return E_FAIL; + } + return S_OK; +} + +HRESULT uiprivTableGetMetrics(uiTable *t, int iItem, int iSubItem, uiprivTableMetrics **mout) +{ + uiprivTableMetrics *m; + uiprivTableColumnParams *p; + LRESULT state; + HWND header; + RECT r; + HRESULT hr; + + if (mout == NULL) + return E_POINTER; + + m = uiprivNew(uiprivTableMetrics); + + p = (*(t->columns))[iSubItem]; + m->hasText = p->textModelColumn != -1; + m->hasImage = (p->imageModelColumn != -1) || (p->checkboxModelColumn != -1); + state = SendMessageW(t->hwnd, LVM_GETITEMSTATE, iItem, LVIS_FOCUSED | LVIS_SELECTED); + m->focused = (state & LVIS_FOCUSED) != 0; + m->selected = (state & LVIS_SELECTED) != 0; + + // TODO check LRESULT bad parameters here + hr = itemRect(S_OK, t, LVM_GETITEMRECT, iItem, + LVIR_BOUNDS, 0, FALSE, &(m->itemBounds)); + hr = itemRect(hr, t, LVM_GETITEMRECT, iItem, + LVIR_ICON, 0, FALSE, &(m->itemIcon)); + hr = itemRect(hr, t, LVM_GETITEMRECT, iItem, + LVIR_LABEL, 0, FALSE, &(m->itemLabel)); + hr = itemRect(hr, t, LVM_GETSUBITEMRECT, iItem, + LVIR_BOUNDS, iSubItem, 0, &(m->subitemBounds)); + hr = itemRect(hr, t, LVM_GETSUBITEMRECT, iItem, + LVIR_ICON, iSubItem, 0, &(m->subitemIcon)); + if (hr != S_OK) + goto fail; + // LVM_GETSUBITEMRECT treats LVIR_LABEL as the same as + // LVIR_BOUNDS, so we can't use that directly. Instead, let's + // assume the text is immediately after the icon. The correct + // rect will be determined by + // computeOtherRectsAndDrawBackgrounds() above. + m->subitemLabel = m->subitemBounds; + m->subitemLabel.left = m->subitemIcon.right; + // And on iSubItem == 0, LVIF_GETSUBITEMRECT still includes + // all the subitems, which we don't want. + if (iSubItem == 0) { + m->subitemBounds.right = m->itemLabel.right; + m->subitemLabel.right = m->itemLabel.right; + } + + header = (HWND) SendMessageW(t->hwnd, LVM_GETHEADER, 0, 0); + m->bitmapMargin = SendMessageW(header, HDM_GETBITMAPMARGIN, 0, 0); + if (ImageList_GetIconSize(t->imagelist, &(m->cxIcon), &(m->cyIcon)) == 0) { + logLastError(L"ImageList_GetIconSize()"); + hr = E_FAIL; + goto fail; + } + + r = m->subitemLabel; + if (!m->hasText && !m->hasImage) + r = m->subitemBounds; + else if (!m->hasImage && iSubItem != 0) + // By default, this will include images; we're not drawing + // images, so we will manually draw over the image area. + // There's a second part to this; see below. + r.left = m->subitemBounds.left; + m->realTextBackground = r; + + m->realTextRect = r; + // TODO confirm whether this really happens on column 0 as well + if (m->hasImage && iSubItem != 0) + // Normally there's this many hard-coded logical units + // of blank space, followed by the background, followed + // by a bitmap margin's worth of space. This looks bad, + // so we overrule that to start the background immediately + // and the text after the hard-coded amount. + m->realTextRect.left += 2; + else if (iSubItem != 0) + // In the case of subitem text without an image, we draw + // text one bitmap margin away from the left edge. + m->realTextRect.left += m->bitmapMargin; + + *mout = m; + return S_OK; +fail: + uiprivFree(m); + *mout = NULL; + return hr; +} diff --git a/dep/libui/windows/tabpage.cpp b/dep/libui/windows/tabpage.cpp new file mode 100644 index 0000000..c258401 --- /dev/null +++ b/dep/libui/windows/tabpage.cpp @@ -0,0 +1,149 @@ +// 30 may 2015 +#include "uipriv_windows.hpp" + +// TODO refine error handling + +// from http://msdn.microsoft.com/en-us/library/windows/desktop/bb226818%28v=vs.85%29.aspx +#define tabMargin 7 + +static void tabPageMargins(struct tabPage *tp, int *mx, int *my) +{ + uiWindowsSizing sizing; + + *mx = 0; + *my = 0; + if (!tp->margined) + return; + uiWindowsGetSizing(tp->hwnd, &sizing); + *mx = tabMargin; + *my = tabMargin; + uiWindowsSizingDlgUnitsToPixels(&sizing, mx, my); +} + +static void tabPageRelayout(struct tabPage *tp) +{ + RECT r; + int mx, my; + HWND child; + + if (tp->child == NULL) + return; + uiWindowsEnsureGetClientRect(tp->hwnd, &r); + tabPageMargins(tp, &mx, &my); + r.left += mx; + r.top += my; + r.right -= mx; + r.bottom -= my; + child = (HWND) uiControlHandle(tp->child); + uiWindowsEnsureMoveWindowDuringResize(child, r.left, r.top, r.right - r.left, r.bottom - r.top); +} + +// dummy dialog procedure; see below for details +// let's handle parent messages here to avoid needing to subclass +// TODO do we need to handle DM_GETDEFID/DM_SETDEFID here too because of the ES_WANTRETURN stuff at http://blogs.msdn.com/b/oldnewthing/archive/2007/08/20/4470527.aspx? what about multiple default buttons (TODO)? +// TODO we definitely need to do something about edit message handling; it does a fake close of our parent on pressing escape, causing uiWindow to stop responding to maximizes but still respond to events and then die horribly on destruction +static INT_PTR CALLBACK dlgproc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + struct tabPage *tp; + LRESULT lResult; + + if (uMsg == WM_INITDIALOG) { + tp = (struct tabPage *) lParam; + tp->hwnd = hwnd; + SetWindowLongPtrW(hwnd, DWLP_USER, (LONG_PTR) tp); + return TRUE; + } + if (handleParentMessages(hwnd, uMsg, wParam, lParam, &lResult) != FALSE) { + SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, (LONG_PTR) lResult); + return TRUE; + } + if (uMsg == WM_WINDOWPOSCHANGED) { + tp = (struct tabPage *) GetWindowLongPtrW(hwnd, DWLP_USER); + tabPageRelayout(tp); + // pretend the dialog hasn't handled this just in case the system needs to do something special + return FALSE; + } + + // unthemed dialogs don't respond to WM_PRINTCLIENT + // fortunately they don't have any special painting + if (uMsg == WM_PRINTCLIENT) { + // don't worry about the return value; hopefully DefWindowProcW() caught it (if not the dialog procedure itself) + // we COULD paint the dialog background brush ourselves but meh, it works + SendMessageW(hwnd, WM_ERASEBKGND, wParam, lParam); + // and pretend we did nothing just so the themed dialog can still paint its content + // TODO see if w ecan avoid erasing the background in this case in the first place, or if we even need to + return FALSE; + } + + return FALSE; +} + +// because Windows doesn't really support resources in static libraries, we have to embed this directly; oh well +/* +// this is the dialog template used by tab pages; see windows/tabpage.c for details +rcTabPageDialog DIALOGEX 0, 0, 100, 100 +STYLE DS_CONTROL | WS_CHILD | WS_VISIBLE +EXSTYLE WS_EX_CONTROLPARENT +BEGIN + // nothing +END +*/ +static const uint8_t data_rcTabPageDialog[] = { + 0x01, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x01, 0x00, 0x00, 0x04, 0x00, 0x50, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x00, + 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +}; +static_assert(ARRAYSIZE(data_rcTabPageDialog) == 32, "wrong size for resource rcTabPageDialog"); + +struct tabPage *newTabPage(uiControl *child) +{ + struct tabPage *tp; + HRESULT hr; + + tp = uiprivNew(struct tabPage); + + // unfortunately this needs to be a proper dialog for EnableThemeDialogTexture() to work; CreateWindowExW() won't suffice + if (CreateDialogIndirectParamW(hInstance, (const DLGTEMPLATE *) data_rcTabPageDialog, + utilWindow, dlgproc, (LPARAM) tp) == NULL) + logLastError(L"error creating tab page"); + + tp->child = child; + if (tp->child != NULL) { + uiWindowsEnsureSetParentHWND((HWND) uiControlHandle(tp->child), tp->hwnd); + uiWindowsControlAssignSoleControlIDZOrder(uiWindowsControl(tp->child)); + } + + hr = EnableThemeDialogTexture(tp->hwnd, ETDT_ENABLE | ETDT_USETABTEXTURE | ETDT_ENABLETAB); + if (hr != S_OK) + logHRESULT(L"error setting tab page background", hr); + // continue anyway; it'll look wrong but eh + + // and start the tab page hidden + ShowWindow(tp->hwnd, SW_HIDE); + + return tp; +} + +void tabPageDestroy(struct tabPage *tp) +{ + // don't destroy the child with the page + if (tp->child != NULL) + uiWindowsControlSetParentHWND(uiWindowsControl(tp->child), NULL); + // don't call EndDialog(); that's for the DialogBox() family of functions instead of CreateDialog() + uiWindowsEnsureDestroyWindow(tp->hwnd); + uiprivFree(tp); +} + +void tabPageMinimumSize(struct tabPage *tp, int *width, int *height) +{ + int mx, my; + + *width = 0; + *height = 0; + if (tp->child != NULL) + uiWindowsControlMinimumSize(uiWindowsControl(tp->child), width, height); + tabPageMargins(tp, &mx, &my); + *width += 2 * mx; + *height += 2 * my; +} diff --git a/dep/libui/windows/text.cpp b/dep/libui/windows/text.cpp new file mode 100644 index 0000000..eafbe71 --- /dev/null +++ b/dep/libui/windows/text.cpp @@ -0,0 +1,120 @@ +// 9 april 2015 +#include "uipriv_windows.hpp" + +WCHAR *windowTextAndLen(HWND hwnd, LRESULT *len) +{ + LRESULT n; + WCHAR *text; + + n = SendMessageW(hwnd, WM_GETTEXTLENGTH, 0, 0); + if (len != NULL) + *len = n; + // WM_GETTEXTLENGTH does not include the null terminator + text = (WCHAR *) uiprivAlloc((n + 1) * sizeof (WCHAR), "WCHAR[]"); + // note the comparison: the size includes the null terminator, but the return does not + if (GetWindowTextW(hwnd, text, n + 1) != n) { + logLastError(L"error getting window text"); + // on error, return an empty string to be safe + *text = L'\0'; + if (len != NULL) + *len = 0; + } + return text; +} + +WCHAR *windowText(HWND hwnd) +{ + return windowTextAndLen(hwnd, NULL); +} + +void setWindowText(HWND hwnd, WCHAR *wtext) +{ + if (SetWindowTextW(hwnd, wtext) == 0) + logLastError(L"error setting window text"); +} + +void uiFreeText(char *text) +{ + uiprivFree(text); +} + +int uiWindowsWindowTextWidth(HWND hwnd) +{ + LRESULT len; + WCHAR *text; + HDC dc; + HFONT prevfont; + SIZE size; + + size.cx = 0; + size.cy = 0; + + text = windowTextAndLen(hwnd, &len); + if (len == 0) // no text; nothing to do + goto noTextOrError; + + // now we can do the calculations + dc = GetDC(hwnd); + if (dc == NULL) { + logLastError(L"error getting DC"); + // on any error, assume no text + goto noTextOrError; + } + prevfont = (HFONT) SelectObject(dc, hMessageFont); + if (prevfont == NULL) { + logLastError(L"error loading control font into device context"); + ReleaseDC(hwnd, dc); + goto noTextOrError; + } + if (GetTextExtentPoint32W(dc, text, len, &size) == 0) { + logLastError(L"error getting text extent point"); + // continue anyway, assuming size is 0 + size.cx = 0; + size.cy = 0; + } + // continue on errors; we got what we want + if (SelectObject(dc, prevfont) != hMessageFont) + logLastError(L"error restoring previous font into device context"); + if (ReleaseDC(hwnd, dc) == 0) + logLastError(L"error releasing DC"); + + uiprivFree(text); + return size.cx; + +noTextOrError: + uiprivFree(text); + return 0; +} + +char *uiWindowsWindowText(HWND hwnd) +{ + WCHAR *wtext; + char *text; + + wtext = windowText(hwnd); + text = toUTF8(wtext); + uiprivFree(wtext); + return text; +} + +void uiWindowsSetWindowText(HWND hwnd, const char *text) +{ + WCHAR *wtext; + + wtext = toUTF16(text); + setWindowText(hwnd, wtext); + uiprivFree(wtext); +} + +int uiprivStricmp(const char *a, const char *b) +{ + WCHAR *wa, *wb; + int ret; + + wa = toUTF16(a); + wb = toUTF16(b); + ret = _wcsicmp(wa, wb); + uiprivFree(wb); + uiprivFree(wa); + return ret; +} diff --git a/dep/libui/windows/uipriv_windows.hpp b/dep/libui/windows/uipriv_windows.hpp new file mode 100644 index 0000000..52d74c5 --- /dev/null +++ b/dep/libui/windows/uipriv_windows.hpp @@ -0,0 +1,174 @@ +// 21 april 2016 +#include "winapi.hpp" +#include "../ui.h" +#include "../ui_windows.h" +#include "../common/uipriv.h" +#include "resources.hpp" +#include "compilerver.hpp" + +// ui internal window messages +// TODO make these either not messages or WM_USER-based, so we can be sane about reserving WM_APP +enum { + // redirected WM_COMMAND and WM_NOTIFY + msgCOMMAND = WM_APP + 0x40, // start offset just to be safe + msgNOTIFY, + msgHSCROLL, + msgQueued, + msgD2DScratchPaint, + msgD2DScratchLButtonDown, +}; + +// alloc.cpp +extern void initAlloc(void); +extern void uninitAlloc(void); + +// events.cpp +extern BOOL runWM_COMMAND(WPARAM wParam, LPARAM lParam, LRESULT *lResult); +extern BOOL runWM_NOTIFY(WPARAM wParam, LPARAM lParam, LRESULT *lResult); +extern BOOL runWM_HSCROLL(WPARAM wParam, LPARAM lParam, LRESULT *lResult); +extern void issueWM_WININICHANGE(WPARAM wParam, LPARAM lParam); + +// utf16.cpp +#define emptyUTF16() ((WCHAR *) uiprivAlloc(1 * sizeof (WCHAR), "WCHAR[]")) +#define emptyUTF8() ((char *) uiprivAlloc(1 * sizeof (char), "char[]")) +extern WCHAR *toUTF16(const char *str); +extern char *toUTF8(const WCHAR *wstr); +extern WCHAR *utf16dup(const WCHAR *orig); +extern WCHAR *strf(const WCHAR *format, ...); +extern WCHAR *vstrf(const WCHAR *format, va_list ap); +extern char *LFtoCRLF(const char *lfonly); +extern void CRLFtoLF(char *s); +extern WCHAR *ftoutf16(double d); +extern WCHAR *itoutf16(int i); + +// debug.cpp +// see http://stackoverflow.com/questions/14421656/is-there-widely-available-wide-character-variant-of-file +// we turn __LINE__ into a string because PRIiMAX can't be converted to a wide string in MSVC (it seems to be defined as "ll" "i" according to the compiler errors) +// also note the use of __FUNCTION__ here; __func__ doesn't seem to work for some reason +#define _ws2(m) L ## m +#define _ws(m) _ws2(m) +#define _ws2n(m) L ## #m +#define _wsn(m) _ws2n(m) +#define debugargs const WCHAR *file, const WCHAR *line, const WCHAR *func +extern HRESULT _logLastError(debugargs, const WCHAR *s); +#ifdef _MSC_VER +#define logLastError(s) _logLastError(_ws(__FILE__), _wsn(__LINE__), _ws(__FUNCTION__), s) +#else +#define logLastError(s) _logLastError(_ws(__FILE__), _wsn(__LINE__), L"TODO none of the function name macros are macros in MinGW", s) +#endif +extern HRESULT _logHRESULT(debugargs, const WCHAR *s, HRESULT hr); +#ifdef _MSC_VER +#define logHRESULT(s, hr) _logHRESULT(_ws(__FILE__), _wsn(__LINE__), _ws(__FUNCTION__), s, hr) +#else +#define logHRESULT(s, hr) _logHRESULT(_ws(__FILE__), _wsn(__LINE__), L"TODO none of the function name macros are macros in MinGW", s, hr) +#endif + +// winutil.cpp +extern int windowClassOf(HWND hwnd, ...); +extern void mapWindowRect(HWND from, HWND to, RECT *r); +extern DWORD getStyle(HWND hwnd); +extern void setStyle(HWND hwnd, DWORD style); +extern DWORD getExStyle(HWND hwnd); +extern void setExStyle(HWND hwnd, DWORD exstyle); +extern void clientSizeToWindowSize(HWND hwnd, int *width, int *height, BOOL hasMenubar); +extern HWND parentOf(HWND child); +extern HWND parentToplevel(HWND child); +extern void setWindowInsertAfter(HWND hwnd, HWND insertAfter); +extern HWND getDlgItem(HWND hwnd, int id); +extern void invalidateRect(HWND hwnd, RECT *r, BOOL erase); + +// text.cpp +extern WCHAR *windowTextAndLen(HWND hwnd, LRESULT *len); +extern WCHAR *windowText(HWND hwnd); +extern void setWindowText(HWND hwnd, WCHAR *wtext); + +// init.cpp +extern HINSTANCE hInstance; +extern int nCmdShow; +extern HFONT hMessageFont; +extern HBRUSH hollowBrush; +extern uiInitOptions options; + +// utilwin.cpp +extern HWND utilWindow; +extern const char *initUtilWindow(HICON hDefaultIcon, HCURSOR hDefaultCursor); +extern void uninitUtilWindow(void); + +// main.cpp +// TODO how the hell did MSVC accept this without the second uiprivTimer??????? +typedef struct uiprivTimer uiprivTimer; +struct uiprivTimer { + int (*f)(void *); + void *data; +}; +extern int registerMessageFilter(void); +extern void unregisterMessageFilter(void); +extern void uiprivFreeTimer(uiprivTimer *t); +extern void uiprivUninitTimers(void); + +// parent.cpp +extern void paintContainerBackground(HWND hwnd, HDC dc, RECT *paintRect); +extern BOOL handleParentMessages(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *lResult); + +// d2dscratch.cpp +extern ATOM registerD2DScratchClass(HICON hDefaultIcon, HCURSOR hDefaultCursor); +extern void unregisterD2DScratchClass(void); +extern HWND newD2DScratch(HWND parent, RECT *rect, HMENU controlID, SUBCLASSPROC subclass, DWORD_PTR subclassData); + +// area.cpp +#define areaClass L"libui_uiAreaClass" +extern ATOM registerAreaClass(HICON, HCURSOR); +extern void unregisterArea(void); + +// areaevents.cpp +extern BOOL areaFilter(MSG *); + +// window.cpp +extern ATOM registerWindowClass(HICON, HCURSOR); +extern void unregisterWindowClass(void); +extern void ensureMinimumWindowSize(uiWindow *); +extern void disableAllWindowsExcept(uiWindow *which); +extern void enableAllWindowsExcept(uiWindow *which); + +// container.cpp +#define containerClass L"libui_uiContainerClass" +extern ATOM initContainer(HICON, HCURSOR); +extern void uninitContainer(void); + +// tabpage.cpp +struct tabPage { + HWND hwnd; + uiControl *child; + BOOL margined; +}; +extern struct tabPage *newTabPage(uiControl *child); +extern void tabPageDestroy(struct tabPage *tp); +extern void tabPageMinimumSize(struct tabPage *tp, int *width, int *height); + +// colordialog.cpp +struct colorDialogRGBA { + double r; + double g; + double b; + double a; +}; +extern BOOL showColorDialog(HWND parent, struct colorDialogRGBA *c); + +// sizing.cpp +extern void getSizing(HWND hwnd, uiWindowsSizing *sizing, HFONT font); + +// TODO move into a dedicated file abibugs.cpp when we rewrite the drawing code +extern D2D1_SIZE_F realGetSize(ID2D1RenderTarget *rt); + +// TODO +#include "_uipriv_migrate.hpp" + +// draw.cpp +extern ID2D1DCRenderTarget *makeHDCRenderTarget(HDC dc, RECT *r); + +// image.cpp +extern IWICImagingFactory *uiprivWICFactory; +extern HRESULT uiprivInitImage(void); +extern void uiprivUninitImage(void); +extern IWICBitmap *uiprivImageAppropriateForDC(uiImage *i, HDC dc); +extern HRESULT uiprivWICToGDI(IWICBitmap *b, HDC dc, int width, int height, HBITMAP *hb); diff --git a/dep/libui/windows/utf16.cpp b/dep/libui/windows/utf16.cpp new file mode 100644 index 0000000..131759e --- /dev/null +++ b/dep/libui/windows/utf16.cpp @@ -0,0 +1,149 @@ +// 21 april 2016 +#include "uipriv_windows.hpp" + +// see http://stackoverflow.com/a/29556509/3408572 + +WCHAR *toUTF16(const char *str) +{ + WCHAR *wstr; + WCHAR *wp; + size_t n; + uint32_t rune; + + if (*str == '\0') // empty string + return emptyUTF16(); + n = uiprivUTF8UTF16Count(str, 0); + wstr = (WCHAR *) uiprivAlloc((n + 1) * sizeof (WCHAR), "WCHAR[]"); + wp = wstr; + while (*str) { + str = uiprivUTF8DecodeRune(str, 0, &rune); + n = uiprivUTF16EncodeRune(rune, wp); + wp += n; + } + return wstr; +} + +char *toUTF8(const WCHAR *wstr) +{ + char *str; + char *sp; + size_t n; + uint32_t rune; + + if (*wstr == L'\0') // empty string + return emptyUTF8(); + n = uiprivUTF16UTF8Count(wstr, 0); + str = (char *) uiprivAlloc((n + 1) * sizeof (char), "char[]"); + sp = str; + while (*wstr) { + wstr = uiprivUTF16DecodeRune(wstr, 0, &rune); + n = uiprivUTF8EncodeRune(rune, sp); + sp += n; + } + return str; +} + +WCHAR *utf16dup(const WCHAR *orig) +{ + WCHAR *out; + size_t len; + + len = wcslen(orig); + out = (WCHAR *) uiprivAlloc((len + 1) * sizeof (WCHAR), "WCHAR[]"); + wcscpy_s(out, len + 1, orig); + return out; +} + +WCHAR *strf(const WCHAR *format, ...) +{ + va_list ap; + WCHAR *str; + + va_start(ap, format); + str = vstrf(format, ap); + va_end(ap); + return str; +} + +WCHAR *vstrf(const WCHAR *format, va_list ap) +{ + va_list ap2; + WCHAR *buf; + size_t n; + + if (*format == L'\0') + return emptyUTF16(); + + va_copy(ap2, ap); + n = _vscwprintf(format, ap2); + va_end(ap2); + n++; // terminating L'\0' + + buf = (WCHAR *) uiprivAlloc(n * sizeof (WCHAR), "WCHAR[]"); + // includes terminating L'\0' according to example in https://msdn.microsoft.com/en-us/library/xa1a1a6z.aspx + vswprintf_s(buf, n, format, ap); + + return buf; +} + +// TODO merge the following two with the toUTF*()s? + +// Let's shove these utility routines here too. +// Prerequisite: lfonly is UTF-8. +char *LFtoCRLF(const char *lfonly) +{ + char *crlf; + size_t i, len; + char *out; + + len = strlen(lfonly); + crlf = (char *) uiprivAlloc((len * 2 + 1) * sizeof (char), "char[]"); + out = crlf; + for (i = 0; i < len; i++) { + if (*lfonly == '\n') + *crlf++ = '\r'; + *crlf++ = *lfonly++; + } + *crlf = '\0'; + return out; +} + +// Prerequisite: s is UTF-8. +void CRLFtoLF(char *s) +{ + char *t = s; + + for (; *s != '\0'; s++) { + // be sure to preserve \rs that are genuinely there + if (*s == '\r' && *(s + 1) == '\n') + continue; + *t++ = *s; + } + *t = '\0'; + // pad out the rest of t, just to be safe + while (t != s) + *t++ = '\0'; +} + +// std::to_string() always uses %f; we want %g +// fortunately std::iostream seems to use %g by default so +WCHAR *ftoutf16(double d) +{ + std::wostringstream ss; + std::wstring s; + + ss << d; + s = ss.str(); // to be safe + return utf16dup(s.c_str()); +} + +// to complement the above +WCHAR *itoutf16(int i) +{ + std::wostringstream ss; + std::wstring s; + + ss << i; + s = ss.str(); // to be safe + return utf16dup(s.c_str()); +} diff --git a/dep/libui/windows/utilwin.cpp b/dep/libui/windows/utilwin.cpp new file mode 100644 index 0000000..0818375 --- /dev/null +++ b/dep/libui/windows/utilwin.cpp @@ -0,0 +1,86 @@ +// 14 may 2015 +#include "uipriv_windows.hpp" + +// The utility window is a special window that performs certain tasks internal to libui. +// It is not a message-only window, and it is always hidden and disabled. +// Its roles: +// - It is the initial parent of all controls. When a control loses its parent, it also becomes that control's parent. +// - It handles WM_QUERYENDSESSION requests. +// - It handles WM_WININICHANGE and forwards the message to any child windows that request it. +// - It handles executing functions queued to run by uiQueueMain(). +// TODO explain why it isn't message-only + +#define utilWindowClass L"libui_utilWindowClass" + +HWND utilWindow; + +static LRESULT CALLBACK utilWindowWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + void (*qf)(void *); + LRESULT lResult; + uiprivTimer *timer; + + if (handleParentMessages(hwnd, uMsg, wParam, lParam, &lResult) != FALSE) + return lResult; + switch (uMsg) { + case WM_QUERYENDSESSION: + // TODO block handler (TODO figure out if this meant the Vista-style block handler or not) + if (uiprivShouldQuit()) { + uiQuit(); + return TRUE; + } + return FALSE; + case WM_WININICHANGE: + issueWM_WININICHANGE(wParam, lParam); + return 0; + case msgQueued: + qf = (void (*)(void *)) wParam; + (*qf)((void *) lParam); + return 0; + case WM_TIMER: + timer = (uiprivTimer *) wParam; + if (!(*(timer->f))(timer->data)) { + if (KillTimer(utilWindow, (UINT_PTR) timer) == 0) + logLastError(L"error calling KillTimer() to end uiTimer() procedure"); + uiprivFreeTimer(timer); + } + return 0; + } + return DefWindowProcW(hwnd, uMsg, wParam, lParam); +} + +const char *initUtilWindow(HICON hDefaultIcon, HCURSOR hDefaultCursor) +{ + WNDCLASSW wc; + + ZeroMemory(&wc, sizeof (WNDCLASSW)); + wc.lpszClassName = utilWindowClass; + wc.lpfnWndProc = utilWindowWndProc; + wc.hInstance = hInstance; + wc.hIcon = hDefaultIcon; + wc.hCursor = hDefaultCursor; + wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1); + if (RegisterClass(&wc) == 0) + // see init.cpp for an explanation of the =s + return "=registering utility window class"; + + utilWindow = CreateWindowExW(0, + utilWindowClass, L"libui utility window", + WS_OVERLAPPEDWINDOW, + 0, 0, 100, 100, + NULL, NULL, hInstance, NULL); + if (utilWindow == NULL) + return "=creating utility window"; + // and just to be safe + EnableWindow(utilWindow, FALSE); + + return NULL; +} + +void uninitUtilWindow(void) +{ + if (DestroyWindow(utilWindow) == 0) + logLastError(L"error destroying utility window"); + if (UnregisterClass(utilWindowClass, hInstance) == 0) + logLastError(L"error unregistering utility window class"); +} diff --git a/dep/libui/windows/winapi.hpp b/dep/libui/windows/winapi.hpp new file mode 100644 index 0000000..b6f2470 --- /dev/null +++ b/dep/libui/windows/winapi.hpp @@ -0,0 +1,64 @@ +// 31 may 2015 +#define UNICODE +#define _UNICODE +#define STRICT +#define STRICT_TYPED_ITEMIDS + +// see https://github.com/golang/go/issues/9916#issuecomment-74812211 +// TODO get rid of this +#define INITGUID + +// for the manifest +#ifndef _UI_STATIC +#define ISOLATION_AWARE_ENABLED 1 +#endif + +// get Windows version right; right now Windows Vista +// unless otherwise stated, all values from Microsoft's sdkddkver.h +// TODO is all of this necessary? how is NTDDI_VERSION used? +// TODO platform update sp2 +#define WINVER 0x0600 /* from Microsoft's winnls.h */ +#define _WIN32_WINNT 0x0600 +#define _WIN32_WINDOWS 0x0600 /* from Microsoft's pdh.h */ +#define _WIN32_IE 0x0700 +#define NTDDI_VERSION 0x06000000 + +// The MinGW-w64 header has an unverified IDWriteTypography definition. +// TODO I can confirm this myself, but I don't know how long it will take for them to note my adjustments... Either way, I have to confirm this myself. +// TODO change the check from _MSC_VER to a MinGW-w64-specific check +// TODO keep track of what else is guarded by this +#ifndef _MSC_VER +#define __MINGW_USE_BROKEN_INTERFACE +#endif + +#include + +// Microsoft's resource compiler will segfault if we feed it headers it was not designed to handle +#ifndef RC_INVOKED +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#endif diff --git a/dep/libui/windows/window.cpp b/dep/libui/windows/window.cpp new file mode 100644 index 0000000..2ea5b7c --- /dev/null +++ b/dep/libui/windows/window.cpp @@ -0,0 +1,536 @@ +// 27 april 2015 +#include "uipriv_windows.hpp" + +#define windowClass L"libui_uiWindowClass" + +struct uiWindow { + uiWindowsControl c; + HWND hwnd; + HMENU menubar; + uiControl *child; + BOOL shownOnce; + int visible; + int (*onClosing)(uiWindow *, void *); + void *onClosingData; + int margined; + BOOL hasMenubar; + void (*onContentSizeChanged)(uiWindow *, void *); + void *onContentSizeChangedData; + BOOL changingSize; + int fullscreen; + WINDOWPLACEMENT fsPrevPlacement; + int borderless; +}; + +// from https://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing +#define windowMargin 7 + +static void windowMargins(uiWindow *w, int *mx, int *my) +{ + uiWindowsSizing sizing; + + *mx = 0; + *my = 0; + if (!w->margined) + return; + uiWindowsGetSizing(w->hwnd, &sizing); + *mx = windowMargin; + *my = windowMargin; + uiWindowsSizingDlgUnitsToPixels(&sizing, mx, my); +} + +static void windowRelayout(uiWindow *w) +{ + int x, y, width, height; + RECT r; + int mx, my; + HWND child; + + if (w->child == NULL) + return; + x = 0; + y = 0; + uiWindowsEnsureGetClientRect(w->hwnd, &r); + width = r.right - r.left; + height = r.bottom - r.top; + windowMargins(w, &mx, &my); + x += mx; + y += my; + width -= 2 * mx; + height -= 2 * my; + child = (HWND) uiControlHandle(w->child); + uiWindowsEnsureMoveWindowDuringResize(child, x, y, width, height); +} + +static LRESULT CALLBACK windowWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + LONG_PTR ww; + uiWindow *w; + CREATESTRUCTW *cs = (CREATESTRUCTW *) lParam; + WINDOWPOS *wp = (WINDOWPOS *) lParam; + MINMAXINFO *mmi = (MINMAXINFO *) lParam; + int width, height; + LRESULT lResult; + + ww = GetWindowLongPtrW(hwnd, GWLP_USERDATA); + if (ww == 0) { + if (uMsg == WM_CREATE) + SetWindowLongPtrW(hwnd, GWLP_USERDATA, (LONG_PTR) (cs->lpCreateParams)); + // fall through to DefWindowProc() anyway + return DefWindowProcW(hwnd, uMsg, wParam, lParam); + } + w = uiWindow((void *) ww); + if (handleParentMessages(hwnd, uMsg, wParam, lParam, &lResult) != FALSE) + return lResult; + switch (uMsg) { + case WM_COMMAND: + // not a menu + if (lParam != 0) + break; + // IsDialogMessage() will also generate IDOK and IDCANCEL when pressing Enter and Escape (respectively) on some controls, like EDIT controls + // swallow those too; they'll cause runMenuEvent() to panic + // TODO fix the root cause somehow + if (HIWORD(wParam) != 0 || LOWORD(wParam) <= IDCANCEL) + break; + runMenuEvent(LOWORD(wParam), uiWindow(w)); + return 0; + case WM_WINDOWPOSCHANGED: + if ((wp->flags & SWP_NOSIZE) != 0) + break; + if (w->onContentSizeChanged != NULL) // TODO figure out why this is happening too early + if (!w->changingSize) + (*(w->onContentSizeChanged))(w, w->onContentSizeChangedData); + windowRelayout(w); + return 0; + case WM_GETMINMAXINFO: + // ensure the user cannot resize the window smaller than its minimum size + lResult = DefWindowProcW(hwnd, uMsg, wParam, lParam); + uiWindowsControlMinimumSize(uiWindowsControl(w), &width, &height); + // width and height are in client coordinates; ptMinTrackSize is in window coordinates + clientSizeToWindowSize(w->hwnd, &width, &height, w->hasMenubar); + mmi->ptMinTrackSize.x = width; + mmi->ptMinTrackSize.y = height; + return lResult; + case WM_PRINTCLIENT: + // we do no special painting; just erase the background + // don't worry about the return value; we let DefWindowProcW() handle this message + SendMessageW(hwnd, WM_ERASEBKGND, wParam, lParam); + return 0; + case WM_CLOSE: + if ((*(w->onClosing))(w, w->onClosingData)) + uiControlDestroy(uiControl(w)); + return 0; // we destroyed it already + } + return DefWindowProcW(hwnd, uMsg, wParam, lParam); +} + +ATOM registerWindowClass(HICON hDefaultIcon, HCURSOR hDefaultCursor) +{ + WNDCLASSW wc; + + ZeroMemory(&wc, sizeof (WNDCLASSW)); + wc.lpszClassName = windowClass; + wc.lpfnWndProc = windowWndProc; + wc.hInstance = hInstance; + wc.hIcon = hDefaultIcon; + wc.hCursor = hDefaultCursor; + wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1); + return RegisterClassW(&wc); +} + +void unregisterWindowClass(void) +{ + if (UnregisterClassW(windowClass, hInstance) == 0) + logLastError(L"error unregistering uiWindow window class"); +} + +static int defaultOnClosing(uiWindow *w, void *data) +{ + return 0; +} + +static void defaultOnPositionContentSizeChanged(uiWindow *w, void *data) +{ + // do nothing +} + +static std::map windows; + +static void uiWindowDestroy(uiControl *c) +{ + uiWindow *w = uiWindow(c); + + // first hide ourselves + ShowWindow(w->hwnd, SW_HIDE); + // now destroy the child + if (w->child != NULL) { + uiControlSetParent(w->child, NULL); + uiControlDestroy(w->child); + } + // now free the menubar, if any + if (w->menubar != NULL) + freeMenubar(w->menubar); + // and finally free ourselves + windows.erase(w); + uiWindowsEnsureDestroyWindow(w->hwnd); + uiFreeControl(uiControl(w)); +} + +uiWindowsControlDefaultHandle(uiWindow) + +uiControl *uiWindowParent(uiControl *c) +{ + return NULL; +} + +void uiWindowSetParent(uiControl *c, uiControl *parent) +{ + uiUserBugCannotSetParentOnToplevel("uiWindow"); +} + +static int uiWindowToplevel(uiControl *c) +{ + return 1; +} + +// TODO initial state of windows is hidden; ensure this here and make it so on other platforms +static int uiWindowVisible(uiControl *c) +{ + uiWindow *w = uiWindow(c); + + return w->visible; +} + +static void uiWindowShow(uiControl *c) +{ + uiWindow *w = uiWindow(c); + + w->visible = 1; + // just in case the window's minimum size wasn't recalculated already + ensureMinimumWindowSize(w); + if (w->shownOnce) { + ShowWindow(w->hwnd, SW_SHOW); + return; + } + w->shownOnce = TRUE; + // make sure the child is the correct size + uiWindowsControlMinimumSizeChanged(uiWindowsControl(w)); + ShowWindow(w->hwnd, nCmdShow); + if (UpdateWindow(w->hwnd) == 0) + logLastError(L"error calling UpdateWindow() after showing uiWindow for the first time"); +} + +static void uiWindowHide(uiControl *c) +{ + uiWindow *w = uiWindow(c); + + w->visible = 0; + ShowWindow(w->hwnd, SW_HIDE); +} + +// TODO we don't want the window to be disabled completely; that would prevent it from being moved! ...would it? +uiWindowsControlDefaultEnabled(uiWindow) +uiWindowsControlDefaultEnable(uiWindow) +uiWindowsControlDefaultDisable(uiWindow) +// TODO we need to do something about undocumented fields in the OS control types +uiWindowsControlDefaultSyncEnableState(uiWindow) +// TODO +uiWindowsControlDefaultSetParentHWND(uiWindow) + +static void uiWindowMinimumSize(uiWindowsControl *c, int *width, int *height) +{ + uiWindow *w = uiWindow(c); + int mx, my; + + *width = 0; + *height = 0; + if (w->child != NULL) + uiWindowsControlMinimumSize(uiWindowsControl(w->child), width, height); + windowMargins(w, &mx, &my); + *width += 2 * mx; + *height += 2 * my; +} + +static void uiWindowMinimumSizeChanged(uiWindowsControl *c) +{ + uiWindow *w = uiWindow(c); + + if (uiWindowsControlTooSmall(uiWindowsControl(w))) { + // TODO figure out what to do with this function + // maybe split it into two so WM_GETMINMAXINFO can use it? + ensureMinimumWindowSize(w); + return; + } + // otherwise we only need to re-layout everything + windowRelayout(w); +} + +static void uiWindowLayoutRect(uiWindowsControl *c, RECT *r) +{ + uiWindow *w = uiWindow(c); + + // the layout rect is the client rect in this case + uiWindowsEnsureGetClientRect(w->hwnd, r); +} + +uiWindowsControlDefaultAssignControlIDZOrder(uiWindow) + +static void uiWindowChildVisibilityChanged(uiWindowsControl *c) +{ + // TODO eliminate the redundancy + uiWindowsControlMinimumSizeChanged(c); +} + +char *uiWindowTitle(uiWindow *w) +{ + return uiWindowsWindowText(w->hwnd); +} + +void uiWindowSetTitle(uiWindow *w, const char *title) +{ + uiWindowsSetWindowText(w->hwnd, title); + // don't queue resize; the caption isn't part of what affects layout and sizing of the client area (it'll be ellipsized if too long) +} + +// this is used for both fullscreening and centering +// see also https://blogs.msdn.microsoft.com/oldnewthing/20100412-00/?p=14353 and https://blogs.msdn.microsoft.com/oldnewthing/20050505-04/?p=35703 +static void windowMonitorRect(HWND hwnd, RECT *r) +{ + HMONITOR monitor; + MONITORINFO mi; + + monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTOPRIMARY); + ZeroMemory(&mi, sizeof (MONITORINFO)); + mi.cbSize = sizeof (MONITORINFO); + if (GetMonitorInfoW(monitor, &mi) == 0) { + logLastError(L"error getting window monitor rect"); + // default to SM_CXSCREEN x SM_CYSCREEN to be safe + r->left = 0; + r->top = 0; + r->right = GetSystemMetrics(SM_CXSCREEN); + r->bottom = GetSystemMetrics(SM_CYSCREEN); + return; + } + *r = mi.rcMonitor; +} + +void uiWindowContentSize(uiWindow *w, int *width, int *height) +{ + RECT r; + + uiWindowsEnsureGetClientRect(w->hwnd, &r); + *width = r.right - r.left; + *height = r.bottom - r.top; +} + +// TODO should this disallow too small? +void uiWindowSetContentSize(uiWindow *w, int width, int height) +{ + w->changingSize = TRUE; + clientSizeToWindowSize(w->hwnd, &width, &height, w->hasMenubar); + if (SetWindowPos(w->hwnd, NULL, 0, 0, width, height, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER) == 0) + logLastError(L"error resizing window"); + w->changingSize = FALSE; +} + +int uiWindowFullscreen(uiWindow *w) +{ + return w->fullscreen; +} + +void uiWindowSetFullscreen(uiWindow *w, int fullscreen) +{ + RECT r; + + if (w->fullscreen && fullscreen) + return; + if (!w->fullscreen && !fullscreen) + return; + w->fullscreen = fullscreen; + w->changingSize = TRUE; + if (w->fullscreen) { + ZeroMemory(&(w->fsPrevPlacement), sizeof (WINDOWPLACEMENT)); + w->fsPrevPlacement.length = sizeof (WINDOWPLACEMENT); + if (GetWindowPlacement(w->hwnd, &(w->fsPrevPlacement)) == 0) + logLastError(L"error getting old window placement"); + windowMonitorRect(w->hwnd, &r); + setStyle(w->hwnd, getStyle(w->hwnd) & ~WS_OVERLAPPEDWINDOW); + if (SetWindowPos(w->hwnd, HWND_TOP, + r.left, r.top, + r.right - r.left, r.bottom - r.top, + SWP_FRAMECHANGED | SWP_NOOWNERZORDER) == 0) + logLastError(L"error making window fullscreen"); + } else { + if (!w->borderless) // keep borderless until that is turned off + setStyle(w->hwnd, getStyle(w->hwnd) | WS_OVERLAPPEDWINDOW); + if (SetWindowPlacement(w->hwnd, &(w->fsPrevPlacement)) == 0) + logLastError(L"error leaving fullscreen"); + if (SetWindowPos(w->hwnd, NULL, + 0, 0, 0, 0, + SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOZORDER) == 0) + logLastError(L"error restoring window border after fullscreen"); + } + w->changingSize = FALSE; +} + +void uiWindowOnContentSizeChanged(uiWindow *w, void (*f)(uiWindow *, void *), void *data) +{ + w->onContentSizeChanged = f; + w->onContentSizeChangedData = data; +} + +void uiWindowOnClosing(uiWindow *w, int (*f)(uiWindow *, void *), void *data) +{ + w->onClosing = f; + w->onClosingData = data; +} + +int uiWindowBorderless(uiWindow *w) +{ + return w->borderless; +} + +// TODO window should move to the old client position and should not have the extra space the borders left behind +// TODO extract the relevant styles from WS_OVERLAPPEDWINDOW? +void uiWindowSetBorderless(uiWindow *w, int borderless) +{ + w->borderless = borderless; + if (w->borderless) + setStyle(w->hwnd, getStyle(w->hwnd) & ~WS_OVERLAPPEDWINDOW); + else + if (!w->fullscreen) // keep borderless until leaving fullscreen + setStyle(w->hwnd, getStyle(w->hwnd) | WS_OVERLAPPEDWINDOW); +} + +void uiWindowSetChild(uiWindow *w, uiControl *child) +{ + if (w->child != NULL) { + uiControlSetParent(w->child, NULL); + uiWindowsControlSetParentHWND(uiWindowsControl(w->child), NULL); + } + w->child = child; + if (w->child != NULL) { + uiControlSetParent(w->child, uiControl(w)); + uiWindowsControlSetParentHWND(uiWindowsControl(w->child), w->hwnd); + uiWindowsControlAssignSoleControlIDZOrder(uiWindowsControl(w->child)); + windowRelayout(w); + } +} + +int uiWindowMargined(uiWindow *w) +{ + return w->margined; +} + +void uiWindowSetMargined(uiWindow *w, int margined) +{ + w->margined = margined; + windowRelayout(w); +} + +// see http://blogs.msdn.com/b/oldnewthing/archive/2003/09/11/54885.aspx and http://blogs.msdn.com/b/oldnewthing/archive/2003/09/13/54917.aspx +// TODO use clientSizeToWindowSize() +static void setClientSize(uiWindow *w, int width, int height, BOOL hasMenubar, DWORD style, DWORD exstyle) +{ + RECT window; + + window.left = 0; + window.top = 0; + window.right = width; + window.bottom = height; + if (AdjustWindowRectEx(&window, style, hasMenubar, exstyle) == 0) + logLastError(L"error getting real window coordinates"); + if (hasMenubar) { + RECT temp; + + temp = window; + temp.bottom = 0x7FFF; // infinite height + SendMessageW(w->hwnd, WM_NCCALCSIZE, (WPARAM) FALSE, (LPARAM) (&temp)); + window.bottom += temp.top; + } + if (SetWindowPos(w->hwnd, NULL, 0, 0, window.right - window.left, window.bottom - window.top, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER) == 0) + logLastError(L"error resizing window"); +} + +uiWindow *uiNewWindow(const char *title, int width, int height, int hasMenubar) +{ + uiWindow *w; + WCHAR *wtitle; + BOOL hasMenubarBOOL; + + uiWindowsNewControl(uiWindow, w); + + hasMenubarBOOL = FALSE; + if (hasMenubar) + hasMenubarBOOL = TRUE; + w->hasMenubar = hasMenubarBOOL; + +#define style WS_OVERLAPPEDWINDOW +#define exstyle 0 + + wtitle = toUTF16(title); + w->hwnd = CreateWindowExW(exstyle, + windowClass, wtitle, + style, + CW_USEDEFAULT, CW_USEDEFAULT, + // use the raw width and height for now + // this will get CW_USEDEFAULT (hopefully) predicting well + // even if it doesn't, we're adjusting it later + width, height, + NULL, NULL, hInstance, w); + if (w->hwnd == NULL) + logLastError(L"error creating window"); + uiprivFree(wtitle); + + if (hasMenubar) { + w->menubar = makeMenubar(); + if (SetMenu(w->hwnd, w->menubar) == 0) + logLastError(L"error giving menu to window"); + } + + // and use the proper size + setClientSize(w, width, height, hasMenubarBOOL, style, exstyle); + + uiWindowOnClosing(w, defaultOnClosing, NULL); + uiWindowOnContentSizeChanged(w, defaultOnPositionContentSizeChanged, NULL); + + windows[w] = true; + return w; +} + +// this cannot queue a resize because it's called by the resize handler +void ensureMinimumWindowSize(uiWindow *w) +{ + int width, height; + RECT r; + + uiWindowsControlMinimumSize(uiWindowsControl(w), &width, &height); + uiWindowsEnsureGetClientRect(w->hwnd, &r); + if (width < (r.right - r.left)) // preserve width if larger + width = r.right - r.left; + if (height < (r.bottom - r.top)) // preserve height if larger + height = r.bottom - r.top; + clientSizeToWindowSize(w->hwnd, &width, &height, w->hasMenubar); + if (SetWindowPos(w->hwnd, NULL, 0, 0, width, height, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER) == 0) + logLastError(L"error resizing window"); +} + +void disableAllWindowsExcept(uiWindow *which) +{ + for (auto &w : windows) { + if (w.first == which) + continue; + EnableWindow(w.first->hwnd, FALSE); + } +} + +void enableAllWindowsExcept(uiWindow *which) +{ + for (auto &w : windows) { + if (w.first == which) + continue; + if (!uiControlEnabled(uiControl(w.first))) + continue; + EnableWindow(w.first->hwnd, TRUE); + } +} diff --git a/dep/libui/windows/winpublic.cpp b/dep/libui/windows/winpublic.cpp new file mode 100644 index 0000000..397a3b5 --- /dev/null +++ b/dep/libui/windows/winpublic.cpp @@ -0,0 +1,61 @@ +// 6 april 2015 +#include "uipriv_windows.hpp" + +void uiWindowsEnsureDestroyWindow(HWND hwnd) +{ + if (DestroyWindow(hwnd) == 0) + logLastError(L"error destroying window"); +} + +void uiWindowsEnsureSetParentHWND(HWND hwnd, HWND parent) +{ + if (parent == NULL) + parent = utilWindow; + if (SetParent(hwnd, parent) == 0) + logLastError(L"error setting window parent"); +} + +void uiWindowsEnsureAssignControlIDZOrder(HWND hwnd, LONG_PTR *controlID, HWND *insertAfter) +{ + SetWindowLongPtrW(hwnd, GWLP_ID, *controlID); + (*controlID)++; + setWindowInsertAfter(hwnd, *insertAfter); + *insertAfter = hwnd; +} + +void uiWindowsEnsureMoveWindowDuringResize(HWND hwnd, int x, int y, int width, int height) +{ + RECT r; + + r.left = x; + r.top = y; + r.right = x + width; + r.bottom = y + height; + if (SetWindowPos(hwnd, NULL, r.left, r.top, r.right - r.left, r.bottom - r.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER) == 0) + logLastError(L"error moving window"); +} + +// do these function even error out in any case other than invalid parameters?! I thought all windows had rects +void uiWindowsEnsureGetClientRect(HWND hwnd, RECT *r) +{ + if (GetClientRect(hwnd, r) == 0) { + logLastError(L"error getting window client rect"); + // zero out the rect on error just to be safe + r->left = 0; + r->top = 0; + r->right = 0; + r->bottom = 0; + } +} + +void uiWindowsEnsureGetWindowRect(HWND hwnd, RECT *r) +{ + if (GetWindowRect(hwnd, r) == 0) { + logLastError(L"error getting window rect"); + // zero out the rect on error just to be safe + r->left = 0; + r->top = 0; + r->right = 0; + r->bottom = 0; + } +} diff --git a/dep/libui/windows/winutil.cpp b/dep/libui/windows/winutil.cpp new file mode 100644 index 0000000..67f0606 --- /dev/null +++ b/dep/libui/windows/winutil.cpp @@ -0,0 +1,154 @@ +// 6 april 2015 +#include "uipriv_windows.hpp" + +// this is a helper function that takes the logic of determining window classes and puts it all in one place +// there are a number of places where we need to know what window class an arbitrary handle has +// theoretically we could use the class atom to avoid a _wcsicmp() +// however, raymond chen advises against this - http://blogs.msdn.com/b/oldnewthing/archive/2004/10/11/240744.aspx (and we're not in control of the Tab class, before you say anything) +// usage: windowClassOf(hwnd, L"class 1", L"class 2", ..., NULL) +int windowClassOf(HWND hwnd, ...) +{ +// MSDN says 256 is the maximum length of a class name; add a few characters just to be safe (because it doesn't say whether this includes the terminating null character) +#define maxClassName 260 + WCHAR classname[maxClassName + 1]; + va_list ap; + WCHAR *curname; + int i; + + if (GetClassNameW(hwnd, classname, maxClassName) == 0) { + logLastError(L"error getting name of window class"); + // assume no match on error, just to be safe + return -1; + } + va_start(ap, hwnd); + i = 0; + for (;;) { + curname = va_arg(ap, WCHAR *); + if (curname == NULL) + break; + if (_wcsicmp(classname, curname) == 0) { + va_end(ap); + return i; + } + i++; + } + // no match + va_end(ap); + return -1; +} + +// wrapper around MapWindowRect() that handles the complex error handling +void mapWindowRect(HWND from, HWND to, RECT *r) +{ + RECT prevr; + DWORD le; + + prevr = *r; + SetLastError(0); + if (MapWindowRect(from, to, r) == 0) { + le = GetLastError(); + SetLastError(le); // just to be safe + if (le != 0) { + logLastError(L"error calling MapWindowRect()"); + // restore original rect on error, just in case + *r = prevr; + } + } +} + +DWORD getStyle(HWND hwnd) +{ + return (DWORD) GetWindowLongPtrW(hwnd, GWL_STYLE); +} + +void setStyle(HWND hwnd, DWORD style) +{ + SetWindowLongPtrW(hwnd, GWL_STYLE, (LONG_PTR) style); +} + +DWORD getExStyle(HWND hwnd) +{ + return (DWORD) GetWindowLongPtrW(hwnd, GWL_EXSTYLE); +} + +void setExStyle(HWND hwnd, DWORD exstyle) +{ + SetWindowLongPtrW(hwnd, GWL_EXSTYLE, (LONG_PTR) exstyle); +} + +// see http://blogs.msdn.com/b/oldnewthing/archive/2003/09/11/54885.aspx and http://blogs.msdn.com/b/oldnewthing/archive/2003/09/13/54917.aspx +void clientSizeToWindowSize(HWND hwnd, int *width, int *height, BOOL hasMenubar) +{ + RECT window; + + window.left = 0; + window.top = 0; + window.right = *width; + window.bottom = *height; + if (AdjustWindowRectEx(&window, getStyle(hwnd), hasMenubar, getExStyle(hwnd)) == 0) { + logLastError(L"error getting adjusted window rect"); + // on error, don't give up; the window will be smaller but whatever + window.left = 0; + window.top = 0; + window.right = *width; + window.bottom = *height; + } + if (hasMenubar) { + RECT temp; + + temp = window; + temp.bottom = 0x7FFF; // infinite height + SendMessageW(hwnd, WM_NCCALCSIZE, (WPARAM) FALSE, (LPARAM) (&temp)); + window.bottom += temp.top; + } + *width = window.right - window.left; + *height = window.bottom - window.top; +} + +HWND parentOf(HWND child) +{ + return GetAncestor(child, GA_PARENT); +} + +HWND parentToplevel(HWND child) +{ + return GetAncestor(child, GA_ROOT); +} + +void setWindowInsertAfter(HWND hwnd, HWND insertAfter) +{ + if (SetWindowPos(hwnd, insertAfter, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOSIZE) == 0) + logLastError(L"error reordering window"); +} + +HWND getDlgItem(HWND hwnd, int id) +{ + HWND out; + + out = GetDlgItem(hwnd, id); + if (out == NULL) + logLastError(L"error getting dialog item handle"); + return out; +} + +void invalidateRect(HWND hwnd, RECT *r, BOOL erase) +{ + if (InvalidateRect(hwnd, r, erase) == 0) + logLastError(L"error invalidating window rect"); +} + +// that damn ABI bug is never going to escape me is it +D2D1_SIZE_F realGetSize(ID2D1RenderTarget *rt) +{ +#ifdef _MSC_VER + return rt->GetSize(); +#else + D2D1_SIZE_F size; + typedef D2D1_SIZE_F *(__stdcall ID2D1RenderTarget::* GetSizeF)(D2D1_SIZE_F *) const; + GetSizeF gs; + + gs = (GetSizeF) (&(rt->GetSize)); + (rt->*gs)(&size); + return size; +#endif +}