titanium how do i add a view to the single context - titanium

So i have a titanium app, and i just read about single contexts. (Incidentally, somebody here should write a book about programming in titanium... the only one out there doesn't really mention single contexts or any of that new-fangled stuff. Heck, make it an eBook. I'd buy it)
The titanium documentation stresses their use (http://docs.appcelerator.com/titanium/latest/#!/guide/Coding_Strategies-section-29004891_CodingStrategies-Executioncontexts) and then politely forgets how to implement a single context!!
So, question:
Let's say i have the awesomeWidget page - this just shows a button, and when you click on a button a new screen appears.
The aswesomeWidget page is accessed through another page - it is not from the root of the titanium app.
Keeping to single contexts, how do i add the view that the button creates to the current window?
Do I:
keep a global pointer to the current (and only) window?
pass the variable holding the current window down to all the following pages that use it
something else?

First off, Titanium keeps a reference to your current window anyway for you, so this use case is easy. For example:
awesomeWidgetButton.addEventListener('click' function(e) {
var yourView = Ti.UI.createView({...});
Titanium.UI.currentWindow.add(yourView);
});
If you want to dig further, the concept of a single context is closely tied to the use of CommonJS modules and the require keyword. It is very simple to keep a single context, just never open a window with the url component filled out, and liberally use the require() keyword. Other than that, its up to your imagination to keep track of who points to what and vice versa, there are standard patterns and best practices that apply here (MVC, Singletons, just keep it simple) just as in coding in any other language.

Related

How can I refresh my composable when new data is being inserted?

My team and I have to make a license plate scanning app as a school project. With that, we have comments and pictures which can be added to cargo. Whenever the user scans a plate they also get the chance to change the checked info in case of a mistake. The problem is that whenever we delete data from the scanned plate it doesn't show on the screen that it has been deleted until we go to another screen. The same goes for the lazy column which we use for inserting new instances of comments and pictures. The data doesn't show on screen until we turn our screen or go back to another screen. private val pictureList = mutableListOf() is what we use for the pictures and for the text we use var countryCode by remember { mutableStateOf(CountryCodeText) }
var licenseNumber by remember { mutableStateOf(LicenseNumberText) }. pictureList is a global variable and the other ones are local variables which use global variables in the mutableStateOf. How can we make sure that the UI updates whenever the data changes? In advance I want to say thanks for the help! (Code is written in Kotlin and jetpack compose)
Just replace the mutableListOf() with a mutableStateListOf(...), and prefer to keep all the state logic confined to a ViewModel. The viewmodel should preferably be only one for the entire app, and the entire app should have only one activity.
The viewmodel should act as a single source of truth for the entire activity's UI state, while also handling all the updates to the UI efficiently.
The #Composables should only be incharge of displaying the state, and sending events to the viewmodel to update the state, for example, an onClick event may be sent up to the viewmodel by a button too trigger a state change in another part of the app.
Take this codelab to learn all about state in Compose (Well, not all, really, but good starter).
Also, changing screens destroys all the #Composables of the current screen, and so when you ce back there, all the #Composables are re-created, and the correct data is fetched. If you wish to trigger "recompositions" upon changing a variable, you must ensure that the concerned variable is a state-holder, i.e., initialized with one of the pre-built state initializers, like mutableStateOf(), or mutableStateMapOf, etc.
We usually have a mutableState*Of format for determining whether a pre-built state initializer is available. The most common ones are covered, obviously, but if not, you'll need to create a new type of initializer yourself, and if that is not something you know how to do, currently, you can just go about checking whether the type of data you wish to store is Immutable. If so, you can just wrap it in a mutableStateOf<DataType>() call, and it will trigger the recompositions. Know that this is not as efficient as pre-built initializers, but definitely gets the job done.
Also, I suggest you take the compose-pathway to get the basics down. It covers everything ranging from creating a simple UI using basic pre-built Layouts to creating a complex animation-driven application using custom Layouts.
So, definitely a lot to take it, but I hope you get there.
Happy composing,

Xcode 7+ Is there a way to Preserve App State after Recompiling

My application has deep navigational chains of 8+ screens deep (Wizard-style). When i'm editing a View Controller, and i want to make a quick visual change and re-test, As a tester, I have to go through the full flow to end up where I was before recompiling, in the same Data state. Is there a way that Xcode can somehow preserve the application state, and re-run the same view controller?
If there was an automated way to detect the last launched screen, and re-display it after the recompile, that would save a lot of developers a lot of time.
I realize something like this can be built custom. Something like:
IF A Certain Debug Flag is ON:
- Retrieve from NSUserDefaults the Class Name of the last controller used, and redisplay it.
The problem with this is: Data State and Navigation State will not be preserved. Also, all other object state which invokes and depends on your controller will not be included. That's why I need a more universal solution.
IF A Certain Debug Flag is ON: - Retrieve from NSUserDefaults the Class Name of the last controller used, and redisplay it.
The problem with this is: Data State and Navigation State will not be preserved.
But this is exactly the problem that the built-in state saving and restoration mechanism is intended to solve, is it not?
https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/PreservingandRestoringState.html
I recommend you use a User Interface target and then create an XCTestCase that works on your view controller and exercise it. Use the new record button in Xcode 7 to get you started with the test case. Familiarize yourself with some of the new queries it uses for some of the dynamic information you may be creating.
Another option would be to inject your test case's UI state into the application delegate in the setup function of an XCTestCase. Then it will need custom logic to navigate to the correct view controller. Then your test case could focus on just that ViewController once the Application delegate has navigated to it.
Of course you can use the debugger and breakpoints in the Test Case and your View Controller while UI Testing. By "scripting" this you do significantly less manual clicking on a device to test a ViewCOntroller
Also you've now got a Test! Hopefully worth something to you down the road when you change something

Controlling level and focus of windows other apps with CGPrivate functions

Question
How to use these private functions on other windows? It would be nice to have this knowledge back in the wild. I am specifically trying to get CGSOrderWindow and CGSSetWindowLevel to work.
I was trying in the direction of:
temporarily register as the dock and then register the dock as the dock again immediately afterwards
or
code injection into the Dock process per this comment:
Also, the author of the above project seems determined to make all core functionality available as a framework. It seems to be implemented as code injection into the Dock process.
Reason I know this is possible
I have been doing work on trying to setLevel on window of another app, and focus window of another app if focused. I am posting this again with the info I learned because from my searching online, I know this was done in the past, its just the knowledge is not publicly out there anymore. The sourceforge pages are no longer there. So I was wondering if you could help me make this information public again.
This is the topic I read that gave me this information - http://cocoadev.com/HowtoControlOtherAppsWindows
Here you see comments like:
You cannot control an another app's windows from a user-level process, unfortunately.
SlavaKarpenko
You can, Slava, you just need to register as the Dock. It might be possible to temporarily register as the dock and then register the dock as the dock again immediately afterwards, not sure. I think the call you'd be wanting to investigate as CoreDockRegisterDockOwner in HIServices.framework.
FinlayDobbie
You could also use APE or similar to do control the windows, or (as mentioned above) register as the Dock (look for the private APIs with Universal Connection in their name). Has anyone found a polite way of getting the Dock to give up its universal connection? The only way I can find is to force quit the Dock and grab the universal connection when it's not looking (which prevents the dock reloading).
SamTaylor
There's an open source project up on sourceforge.net that looks much more like the window managers I've used on Unix boxes than Space.app (or Space.dock): http://wsmanager.sourceforge.net/
SteveCook
Verifying things work
This is what I learned, from the sources at bottom of this post, we see all these functions work with CGWindowIds, so how do I get that, this is how:
Get all windows with CGWindowListCopyWindowInfo. Then access each element from that array with CFArrayGetValueAtIndex and then get the CGWindowId with objectForKey:, kCGWindowNumber, and then integerValue.
Now if I try to focus or set level of a window that is OWNED by the app running the code, it works fantastic. For instance:
MY_TARGET_CGWINDOW_ID = 179;
rez_CGError = CGSOrderWindow(_CGSDefaultConnection, MY_TARGET_CGWINDOW_ID, kCGSOrderAbove, 0);
Will focus it, rez_CGError is 0. Even if the window is minimized, it is unminimized, without animation, and shown.
Now however, if I try this on a window of a different app we get some errors:
MY_TARGET_CGWINDOW_ID_of_other_app = 40;
rez_CGError = CGSOrderWindow(_CGSDefaultConnection, MY_TARGET_CGWINDOW_ID_of_other_app, kCGSOrderAbove, 0);
This fails and rez_CGError is 1000, which I suspect means "cid (CGSConnection) used does not have permission to modify target window". The same happens if I first do [app activateWithOptions: (NSApplicationActivateIgnoringOtherApps | NSApplicationActivateAllWindows)] before making the call above.
So I first get the cid of that owning window like this:
var rez_CGError = CGSGetWindowOwner(_CGSDefaultConnection, MY_TARGET_CGWINDOW_ID_of_other_app, &ownerCid);
This works good and I get ownerCid is set to a value. Then I do the focus command with this new connection:
rez_CGError = CGSOrderWindow(ownerCid, MY_TARGET_CGWINDOW_ID_of_other_app, kCGSOrderAbove, 0);
However this gives rez_CGError of 268435459, which I suspect means "current app does not have permission to use this ConnectionId (cid)". (Same happens if I call activateWithOptions first.
My Sources for the Private Functions
Here is the sources for some private functions I found - https://code.google.com/p/undocumented-goodness/source/browse/trunk/CoreGraphics/CGSPrivate.h
This one source here contains a function that is not in the above link - CGSGetConnectionIDForPSN - i test it and it exists - from - https://github.com/mnutt/libqxt/blob/767498816dfa1742a6f3aee787281745afec11b8/src/gui/qxtwindowsystem_mac.h#L80

How do you know what methods to use for a task?

I am learning Objective-C Cocoa programming for OS X, and object-based programming in general, so I am a big novice here, so my question is a bit general and my guess is the answer to this is simply "experience"; however, I am curious if there is some route of knowledge to understanding what methods in various classes are best or perhaps required for getting tasks done.
For example, in a programming guide I am instructed to create a document-based program, and the document class contains an array to store data, with the following method bound to a button to create a new entry in the array:
- (IBAction)insertItem:(id)sender {
if (!theItems) {
theItems = [NSMutableArray array];
}
[theItems addObject:#"Double-click to edit."];
[theTableView reloadData];
[self updateChangeCount:NSChangeDone];
}
The array is "theItems" and its data is being presented in a TableView object. I understand that the steps here add a new string to the array and then refresh the table to display it, followed by setting the document to be set to an unsaved state.
What I am not getting is how one would know these specific steps and methods are required. Intuitively it seems one would just add items to the array, and that would be all that's required to have the new values simply show up in the table view for which the array is the data source, so how would one know that the tableView would need to be refreshed with the "reloadData" call? I can see someone (myself) figuring it out by trial and error, but is there some quick resource or guide (ie, some quick flow-chart) either in XCode or elsewhere that indicates for a table view that this would have to be a required action to display the new entry?
If I look at Apple's NSTableView class reference, it claims in the overview that you "modify the values in the data source and allow the changes to be reflected in the table view" which suggest the view is updated automatically, so the requirement to call "reloadData" on the view seems a little obscure.
Look for the guides. In the online class reference for NSTableView, there's a section at the top called "Companion Guides". For NSTableView, it lists the Table View Programming Guide for Mac. (In the prerelease 10.10 docs, the guides are listed under Related Documentation in the left-hand sidebar.)
I could have sworn this same information was available in Xcode's Documentation window, albeit somewhat hidden behind a "More related items" pseudo-link, but when I check right now there's no link to the guide anywhere in the NSTableView class reference. Which is a terrible oversight.
You can also browse or search the Guides section of the developer library.
Familiarity, studying the documentation and possibly reading some good books is the answer. For example, in the docs you quoted (emphasis mine)
you should modify the values in the data source and allow the changes to be reflected in the table view
You should do both these things. If you want it to happen "automatically", look into bindings, which uses several other Cocoa features you won't understand at this point either to do the table data source stuff for you. I'd recommend understanding what is happening manually before handing over control to bindings, so you have some chance of understanding when things go wrong.
As well as looking at the table view documentation, you also need to study the cell, delegate and datasource references. All of those objects work together to give you the functioning table view.

EventToCommand binding with parameters in portable view models

I am implementing a view model that is shared by applications on multiple platforms. I am using MvvmCross v3 that has its own MvxEventToCommand class, but I believe the challenge is the same for other frameworks like MVVM Light. As long as the event is used without parameters, the implementation is straightworward, and this is the case for simple interactions like tapping the control.
But when the command needs to handle event arguments things become more complicated. For example, the view model needs to act on certain scroll bar changes (and load more items in the associated list view). Here is the example of XAML:
<cmd:EventToCommand
Command="{Binding ScrollChanged}"
CommandParameter="{Binding EventArgs}" />
(MvvmCross uses MvxEventToCommand, but the principle is the same).
Then in my model I can have the following command handler:
public ICommand ScrollChanged
{
get
{
return new RelayCommand<ScrollChangedEventArgs>(e =>
{
MessageBox.Show("Change!");
});
}
}
(MvxCommand in MvvmCross).
The problem is that ScrollChangedEventArgs is platform specific and this code simply will not compile in a portable class library. This is a general problem with any command that needs not only a push when an event was fired but requires more specific event details. Moving this code in platform-specific part is silly because it more or less kills the concept of portable view models and code-behind-free views. I tried to search for projects that share view models between different platforms, but they all use simple events like "Tap" with no attached event details.
UPDATE 1 I agree with Stuart's remark that view models should only deal with higher level abstractions, so I will rephrase the original concern: how to map results of low-level interactions to a platform-neutral event that triggers a business logic command? Consider the example above: the business logic command is "load more items in a list", i.e. we deal with a list virtualization where a limited number of items from a large collection are loaded initially, and scrolling down to a bottom of a list should cause additional items to be loaded.
WinRT can take care of list virtualization by using observable collections that support ISupportIncrementalLoading interface. The runtime detects this capability and automatically requests extra items from a respective service when the user scrolls down the list. On other platforms this feature should be implemented manually and I can't find any other way than reacting on ScrollViewer ScrollChanged event. I can see then two further options:
Place OnScrollChanged handler in a code-behind file and call the portable view model higher level event (such as "OnItemsRequested");
Avoid code-behind stuff and struggle to wire the ScrollChanged event directly to a view model, then we will need to remap the platform-specific event first.
As long as there is no support for second option, putting event handler in code-behind file is OK as long as it is done for the sole purpose of event mapping. But I would like to investigate what can be done using the second option. MvvmCross has MapCommandParameter class which seems to be able to help, so I wonder if I should exploit that one.
UPDATE 2 I tried MapCommandParameter approach, and it worked allowing me to insert a platform-specific adapter that would map low-level events to view model-specific commands. So the second option worked without any struggle. Stuart also suggested listview-subclassing so there is no need to care about scrolling events. I plan to play with it later.
I agree that viewmodel commands should normally be expressed in terms of viewmodel concepts - so it would be 'strange' to send the viewmodel a command about the scrollbar value changing, but it might be ok to send the viewmodel a command about the user selecting certain list elements to be visible (which she does via scrolling)
One example where I've done this type of thing previously is in list selection.
I originally did this across multiple platforms using a cross-platform eventargs object -
https://github.com/slodge/MvvmCross/blob/vnext/Cirrious/Cirrious.MvvmCross/Commands/MvxSimpleSelectionChangedEventArgs.cs
this was then used on WindowsPhone (for example) via an EventToCommand class like https://github.com/slodge/MvvmCross/blob/vnext/Cirrious/Cirrious.MvvmCross.WindowsPhone/Commands/MvxSelectionChangedEventToCommand.cs
However... I have to admit that this code hasn't been used much... For list selection we have instead mainly used selecteditem binding, and there simply haven't been any apps that have needed more complex parameterized commands (so far) - you might even need to go back to very old v1 mvvmcross code to find any samples that use it.