Detect if printer support duplex programmatically using obj-c - objective-c

I have been stumped by this for the last few days. I need to detect if a printer support duplex printing.
I have had partial success using code like:
NSPrinter * printer = [NSPrinter printerWithName:pname];
[printInfo setPrinter:printer];
PMPrintSettings settings = printInfo.PMPrintSettings;
PMDuplexMode pmDuplexMode = 0;
OSStatus status = PMGetDuplex(settings, &pmDuplexMode);
supportsDuplex = (status >= 0);
But this only work if I captured a full printerConfig through an NSPrintPanel. What I need is a way to detect if a printer with a specific name support duplex without requiring the user to 1st open a panel. I would like to do if for any printer defined on the local Mac. Any help is appreciated!

In your code snippet, I doubt that it's correct to interpret positive status as indicating support. In general, any value other than zero (noErr) is a failure of some sort.
If you're confident that PMGetDuplex() returns an error for a print settings object when the printer doesn't support duplex, you can try this approach: create a session with PMCreateSession(), obtain a PMPrinter using PMPrinterCreateFromPrinterID() or by searching the array returned from PMSessionCreatePrinterList() for on which matches whatever criteria you want, set the session to use that printer using PMSessionSetCurrentPMPrinter(), create a print settings object with PMCreatePrintSettings(), call PMSessionDefaultPrintSettings() to initialize the print settings from the session, call PMSessionValidatePrintSettings() just for good measure, then call PMGetDuplex() and check the return value.
It might also be worth trying to set a duplex mode with PMSetDuplex() and check the return code and, possibly, calling PMSessionValidatePrintSettings() and checking if it changed that setting.

Related

How can I turn on design mode in Gecko?

I am using Gecko browser in my program. I am trying to turn on design mode on this browser like that:
webBrowser1.Document.DomDocument.GetType().GetProperty("designMode").SetValue
(webBrowser1.Document.DomDocument, "On", null);
But it doesn't works. How can I do it?
nsIHTMLEditor is likely a per browser instance rather than a global instance (like things returned by Xpcom.GetService)
One can get a nsIEditor like this by (by supplying a Window instance)
var editingSession = Xpcom.CreateInstance<nsIEditingSession>("#mozilla.org/editor/editingsession;1");
nsIEditor editor = editingSession.GetEditorForWindow((nsIDOMWindow)Window.DomWindow);
Marshal.ReleaseComObject(editingSession);
(or you can just call the nsIEditor GeckoWebBrowser.Editor property.)
You may be able to cast this nsIEditor to a nsIHtmlEditor (although I have yet to try it)
GeckoWebBrowser browser = .....;
// Untested code
nsIHTMLEditor htmlEditor = (nsIHTMLEditor)browser.Editor;
The VB code from #GreenBear
Dim gEditor As nsIHTMLEditor:
gEditor = Gbrowser.Editor:
gEditor.DecreaseFontSize()

Psychopy and pylink example

I'm working on integrating an experiment in psychopy with the eyelink eyetracking system. The way to do this seems to be through pylink. Unfortunately I'm really unfamiliar with pylink and I was hoping there was a sample of an experiment that combines the two. I haven't been able to find one. If anyone would be able to share an example or point me towards a more accessible manual than the pylink api that sr-research provides I'd be really grateful.
Thanks!
I am glad you found your solution. I have not used iohub, but we do use psychopy and an eyelink and therefore some of the following code may be of use to others who wish to invoke more direct communication. Note that our computers use Archlinux. If none of the following makes any sense to you, don't worry about it, but maybe it will help others who are stumbling along the same path we are.
Communication between experimental machine and eye tracker machine
First, you have to establish communication with the eyelink. If your experimental machine is turned on and plugged into a live Eyelink computer then on linux you have to first set your ethernet card up, and then set the default address that Eyelink uses (this also works for the Eyelink 1000 - they kept the same address). Note your ethernet will probably have a different name than enp4s0. Try simply with ip link and look for something similar. NB: these commands are being typed into a terminal.
#To set up connection with Eyelink II computer:
#ip link set enp4s0 up
#ip addr add 100.1.1.2/24 dev enp4s0
Eyetracker functions
We have found it convenient to write some functions for talking to the Eyelink computer. For example:
Initialize Eyetracker
sp refers to the tuple of screenx, screeny sizes.
def eyeTrkInit (sp):
el = pl.EyeLink()
el.sendCommand("screen_pixel_coords = 0 0 %d %d" %sp)
el.sendMessage("DISPLAY_COORDS 0 0 %d %d" %sp)
el.sendCommand("select_parser_configuration 0")
el.sendCommand("scene_camera_gazemap = NO")
el.sendCommand("pupil_size_diameter = %s"%("YES"))
return(el)
NB: the pl function comes from import pylink as pl. Also, note that there is another python library called pylink that you can find on line. It is probably not the one you want. Go through the Eyelink forum and get pylink from there. It is old, but it still works.
Calibrate Eyetracker
el is the name of the eyetracker object initialized above. sp screen size, and cd is color depth, e.g. 32.
def eyeTrkCalib (el,sp,cd):
pl.openGraphics(sp,cd)
pl.setCalibrationColors((255,255,255),(0,0,0))
pl.setTargetSize(int(sp[0]/70), int(sp[1]/300))
pl.setCalibrationSounds("","","")
pl.setDriftCorrectSounds("","off","off")
el.doTrackerSetup()
pl.closeGraphics()
#el.setOfflineMode()
Open datafile
You can talk to the eye tracker and do things like opening a file
def eyeTrkOpenEDF (dfn,el):
el.openDataFile(dfn + '.EDF')
Drift correction
Or drift correct
def driftCor(el,sp,cd):
blockLabel=psychopy.visual.TextStim(expWin,text="Press the space bar to begin drift correction",pos=[0,0], color="white", bold=True,alignHoriz="center",height=0.5)
notdone=True
while notdone:
blockLabel.draw()
expWin.flip()
if keyState[key.SPACE] == True:
eyeTrkCalib(el,sp,cd)
expWin.winHandle.activate()
keyState[key.SPACE] = False
notdone=False
Sending and getting messages.
There are a number of built-in variables you can set, or you can add your own. Here is an example of sending a message from your python program to the eyelink
eyelink.sendMessage("TRIALID "+str(trialnum))
eyelink.startRecording(1,1,1,1)
eyelink.sendMessage("FIX1")
tFix1On=expClock.getTime()
Gaze contingent programming
Here is a portion of some code that uses the eyelink's most recent sample in the logic of the experimental program.
while notdone:
if recalib==True:
dict['recalib']=True
eyelink.sendMessage("RECALIB END")
eyelink.startRecording(1,1,1,1)
recalib=False
eventType=eyelink.getNextData()
if eventType==pl.STARTFIX or eventType==pl.FIXUPDATE or eventType==pl.ENDFIX:
sample=eyelink.getNewestSample()
if sample != None:
if sample.isRightSample():
gazePos = sample.getRightEye().getGaze()
if sample.isLeftSample():
gazePos = sample.getLeftEye().getGaze()
gazePosCorFix = [gazePos[0]-scrx/2,-(gazePos[1]-scry/2)]
posPix = posToPix(fixation)
eucDistFix = sqrt((gazePosCorFix[0]-posPix[0])**2+(gazePosCorFix[1]-posPix[1])**2)
if eucDistFix < tolFix:
core.wait(timeFix1)
notdone=False
eyelink.resetData()
break
Happy Hacking.
rather than PyLink, you might want to look into using the ioHub system within PsychoPy. This is a more general-purpose eye tracking system that also allows for saving data in a common format (integrated with PsychoPy events), and provides tools for data analysis and visualisation.
ioHUb is built to be agnostic to the particular eye tracker you are using. You just need to create a configuration file specific to your EyeLink system, and thereafter use the generic functions ioHiv provides for calibration, accessing gaze data in real-time, and so on.
There are some teaching resources accessible here: http://www.psychopy.org/resources/ECEM_Python_materials.zip
For future readers, I wanted to share my library for combining pylink and psychopy. I've recently updated it to work with python 3. It provides simple to use, high level functions.
https://github.com/colinquirk/templateexperiments/tree/master/eyelinker
You could also work at a lower level with the PsychoPyCustomDisplay class (see the pylink docs for more info about EyeLinkCustomDisplay).
For an example of it in use, see:
https://github.com/colinquirk/ChangeDetectionEyeTracking
(At the time of writing, this experiment code is not yet python 3 ready, but it should still be a useful example.)
The repo also includes other modules for creating experiments and recording EEG data, but they are not necessary if you are just interested in the eyelinker code.

Cannot read second page scanned via ADF

I have a Brother mutlifunction networked printer/scanner/fax (model MFC-9140CDN). I am trying to use the following code with WIA, to retrieve items scanned in with the document feeder:
const int FEEDER = 1;
var manager=new DeviceManager();
var deviceInfo=manager.DeviceInfos.Cast<DeviceInfo>().First();
var device=deviceInfo.Connect();
device.Properties["Pages"].set_Value(1);
device.Properties["Document Handling Select"].set_Value(1);
var morePages=true;
var counter=0;
while (morePages) {
counter++;
var item=device.Items[1];
item.Properties["Bits Per Pixel"].set_Value(1);
item.Properties["Horizontal Resolution"].set_Value(300);
item.Properties["Vertical Resolution"].set_Value(300);
var img=(WIA.ImageFile)item.Transfer();
var path=String.Format(#"C:\Users\user1\Documents\test_{0}.tiff",counter);
img.SaveFile(path);
var status=(int)device.Properties["Document Handling Status"].get_Value();
morePages = (status & FEEDER) > 0;
}
When the Transfer method is reached for the first time, all the pages go through the document feeder. The first page gets saved with img.SaveFile to the passed-in path, but all the subsequent pages are not available - device.Items.Count is 1, and trying device.Items[2] raises an exception.
In the next iteration, calling Transfer raises an exception -- understandably, because there are now no pages in the feeder.
How can I get the subsequent images that have been scanned into the feeder?
(N.B. Iterating through all the device properties, there is an additional unnamed property with the id of 38922. I haven't been able to find any reference to this property.)
Update
I couldn't find a property on the device corresponding to WIA_IPS_SCAN_AHEAD or WIA_DPS_SCAN_AHEAD_PAGES, but that makes sense because this property is optional according to the documentation.
I tried using TWAIN (via the NTwain library, which I highly recommend) with the same problem.
I have recently experienced a similar error with a HP MFC.
It seems that a property was being changed by the driver. The previous developer of the software I'm working on just kept reinitalisating the driver each time in the for loop.
In my case the property was 'Media Type' being set to FLATBED (0x02) even though I was doing a multi-page scan and needed it to be NEXT_PAGE (0x80).
The way I found this was by storing every property before I scanner (both device and item properties) and again after scanning the first page. I then had my application print out any properties that had changed and was able to identify my problem.
This is a networked scanner, and I was using the WSD driver.
Once I installed the manufacturer's driver, the behavior is as expected -- one page goes through the ADF, after which control is returned to the program.
(Even now, when I use WIA's CommonDialog.ShowSelectDevice method, the scanner is available twice, once using the Windows driver and once using the Brother driver; when I choose the WSD driver, I still see the issue.)
This bug did cost me hours...
So thanks a lot Zev.
I also had two scanners shown in the dialog for physically one machine. One driver scans only the first page and then empties the feeder without any chance to intercept. The other one works as expected.
BTW: It is not needed to initialize the scanner for each page. I call my routines for initialization prior to the Transfer() loop. Works just fine.
Another hickup I ran into was to first initialize page sizes, then the feeder. So if you do not get it to work, try switching the sequence how you change the properties for your WIA driver. As mentioned in the MSDN, some properties also influence others, potentially resetting your changes.
So praise to ZEV SPITZ for the answer on Aug. 09, 2015.
You should instantiate and setup device inside the 'while' loop. See:
const int FEEDER = 1;
var morePages=true;
var counter=0;
while (morePages) {
counter++;
var manager=new DeviceManager();
var deviceInfo=manager.DeviceInfos.Cast<DeviceInfo>().First();
var device=deviceInfo.Connect();
//device.Properties["Pages"].set_Value(1);
device.Properties["Document Handling Select"].set_Value(1);
var item=device.Items[1];
item.Properties["Bits Per Pixel"].set_Value(1);
item.Properties["Horizontal Resolution"].set_Value(300);
item.Properties["Vertical Resolution"].set_Value(300);
var img=(WIA.ImageFile)item.Transfer();
var path=String.Format(#"C:\Users\user1\Documents\test_{0}.tiff",counter);
img.SaveFile(path);
var status=(int)device.Properties["Document Handling Status"].get_Value();
morePages = (status & FEEDER) > 0;
}
I got this looking into this free project, which I believe is able to help you too: adfwia.codeplex.com

AHK: Manage multiple scripts

I got many scripts. I want to be able to manage them all in 1 in script.
What I want is that the main script will activate a certain script, then when the secondary script is done, it returns a value to the main script. After that, the main script calls another secondary script, etc...
Is there a proper way to do this?
More precise question:
Is it possible to activate a AHK script from another script AHK?
At the moment, to detect that at a secondary script is complete, the way I currently use is that right before the end of the secondary script, I press a combinaison of keys that the main script will detect. And once detected, it will increase a main script variable by one and this will trigger the activation of the next script. Is there a better way to achieve this?
The main script could call the other scripts using RunWait. The scripts could then communicate back before terminating themselves.
The best option for communication would be to use OnMessage.
The following is a working example from the documentation:
; Example: Send a string of any length from one script to another. This is a working example.
; To use it, save and run both of the following scripts then press Win+Space to show an
; InputBox that will prompt you to type in a string.
; Save the following script as "Receiver.ahk" then launch it:
#SingleInstance
OnMessage(0x4a, "Receive_WM_COPYDATA") ; 0x4a is WM_COPYDATA
return
Receive_WM_COPYDATA(wParam, lParam)
{
StringAddress := NumGet(lParam + 2*A_PtrSize) ; Retrieves the CopyDataStruct's lpData member.
CopyOfData := StrGet(StringAddress) ; Copy the string out of the structure.
; Show it with ToolTip vs. MsgBox so we can return in a timely fashion:
ToolTip %A_ScriptName%`nReceived the following string:`n%CopyOfData%
return true ; Returning 1 (true) is the traditional way to acknowledge this message.
}
; Save the following script as "Sender.ahk" then launch it. After that, press the Win+Space hotkey.
TargetScriptTitle = Receiver.ahk ahk_class AutoHotkey
#space:: ; Win+Space hotkey. Press it to show an InputBox for entry of a message string.
InputBox, StringToSend, Send text via WM_COPYDATA, Enter some text to Send:
if ErrorLevel ; User pressed the Cancel button.
return
result := Send_WM_COPYDATA(StringToSend, TargetScriptTitle)
if result = FAIL
MsgBox SendMessage failed. Does the following WinTitle exist?:`n%TargetScriptTitle%
else if result = 0
MsgBox Message sent but the target window responded with 0, which may mean it ignored it.
return
Send_WM_COPYDATA(ByRef StringToSend, ByRef TargetScriptTitle) ; ByRef saves a little memory in this case.
; This function sends the specified string to the specified window and returns the reply.
; The reply is 1 if the target window processed the message, or 0 if it ignored it.
{
VarSetCapacity(CopyDataStruct, 3*A_PtrSize, 0) ; Set up the structure's memory area.
; First set the structure's cbData member to the size of the string, including its zero terminator:
SizeInBytes := (StrLen(StringToSend) + 1) * (A_IsUnicode ? 2 : 1)
NumPut(SizeInBytes, CopyDataStruct, A_PtrSize) ; OS requires that this be done.
NumPut(&StringToSend, CopyDataStruct, 2*A_PtrSize) ; Set lpData to point to the string itself.
Prev_DetectHiddenWindows := A_DetectHiddenWindows
Prev_TitleMatchMode := A_TitleMatchMode
DetectHiddenWindows On
SetTitleMatchMode 2
SendMessage, 0x4a, 0, &CopyDataStruct,, %TargetScriptTitle% ; 0x4a is WM_COPYDATA. Must use Send not Post.
DetectHiddenWindows %Prev_DetectHiddenWindows% ; Restore original setting for the caller.
SetTitleMatchMode %Prev_TitleMatchMode% ; Same.
return ErrorLevel ; Return SendMessage's reply back to our caller.
}
Well, I'm not sure why you'd want to make one script run another one... but here are a few other methods:
Include a script in another one
but, you know you can include a script inside another one, right? That is, you can use another scripts functions in your main script.
Make sure a particular script is loaded
"I got many scripts" too. Sometimes I need to make sure that a particular one is included before I can use it, so I put this at the top:
;make sure core.ahk is loaded since it is required
#include c:\ahk\core.ahk
And you don't have to worry about it getting included more than once (unless you need it) because:
#Include ensures that FileName is included only once, even if multiple inclusions are encountered for it. By contrast, #IncludeAgain allows
multiple inclusions of the same file, while being the same as #Include
in all other respects.
Now, when I include file.ahk in main.ahk, I am assured of no problems using the functions from core.ahk that file.ahk requires. And even if I include core.ahk again in main.ahk it is no worry (unless it contains subroutines instead of just functions - in which case they get run at the point where they were included, so it's best not to put subroutines in your ahk libraries).
Use good ole' RUN on Scripts
Aside from that, you know you can always use the run command to launch an ahk script. You don't have to do all that fancy WM_SENDMESSAGE stuff.
Communicate betweenst scripts using a hidden GUI
Another way for two scripts to communicate between each other is for script #1 to keep open a hidden GUI window that has an edit box and a submit button. This window will never be shown. Now, Script #2 hunts for that message box, uses send to put a string in the edit box, and then control-click to push the submit button. Now script #1 has just received input from script #2. And you don't even have to hunt for the window if you put the windows hwnd value in both scripts (so they already know it ahead of time). This works like a charm.
Tell if a script has completed
If you use ahk's run command, there is an parameter that will give you back the PID of that process (PID = Process ID). You can use this PID to check to see if the script is running, and you can use it to terminate the process.
Also, if you use runwait - the script using that command will pause and wait for the runn-ed process to complete and close before continuing.
theoretically you could also use a file object between the scripts as a sort of stdin/stdout method as when opening a file with the file object you can set it as shared.
You could also set an environment variable and pass the name of the variable to the script ,given that you have setup argument handling in the target script, which then sets the environment variable value on closing. using RunWait and this you could find out what the return result of the script is after it runs.
Lastly, look into using a function as that is probably the "best practice" for what you are trying to do. Since a function can do anything a script can do and you can pass it an array to operate on or with using ByRef on the array param. This would mean that you don't have to write in a bunch of parameters when writing the function and the variables would release memory once the function is complete, automatically. You can even write your functions in a separate file and use #Include to use them in your script.

Crystal reports 11 RDC (COM API) displays printer dialog even when I tell it not to prompt

I'm using Crystal Reports 11's RDC (COM) API to print. My code looks like this:
HRESULT res = m_Report->SelectPrinter(b_driver, b_device, b_port);
if (FAILED(res)) return res;
// For these calls, the #import wrapper throws on error
m_Report->PutPrinterDuplex(dmDuplex);
m_Report->PutPaperSize(dmPaperSize);
m_Report->PutPaperSource((CRPaperSource)pdlg->GetDevMode()->dmDefaultSource);
if (m_Report->GetPaperOrientation() == crDefaultPaperOrientation)
m_Report->PutPaperOrientation(crPortrait);
VARIANT vfalse;
VariantInit(&vfalse);
vfalse.vt=VT_BOOL;
vfalse.boolVal=0;
res = m_Report->PrintOut(vfalse);
However, at the end of all this, crystal reports still shows its own printer selection dialog - but only for some reports, it seems. Why does crystal reports show a print dialog even when I pass false for promptUser? And how, then, can I suppress crystal reports' internal printer selection dialog and force it to use my values?
Edit: Whoops, CR11, not CR9.
Some further information:
The reports that work properly (ie, do not show the print dialog) are generated internally using the RDC API; we create a new report object, import subreports into it, then print the result. No problem there.
The reports that do not work properly (ie, force the print dialog to open) have been created with a previous version of crystal reports; however, opening and saving the report does not seem to help.
Sample reports in the Crystal Reports installation directory show the same problem.
I tried reproducing with VBScript; however, the result was that nothing was printed at all (no dialog, no nothing):
Set app = CreateObject("CrystalRuntime.Application.11")
Set report = app.OpenReport("C:\Program Files\Business Objects\Crystal Reports 11.5\Samples\en\Reports\General Business\Inventory Crosstab.rpt")
report.PrintOut(True)
rem Testing with a True parameter to force a print dialog - but no printout and nothing appears (no error either though)
First, let me preface that I'm not a C/C++ programmer, so I'm not able to test the code--my interaction w/ the SDK has been with the VB and .Net interface over the years.
I found the following code from BO's devlibrary:
// A dummy variant
VariantInit (&dummy);
dummy.vt = VT_EMPTY;
HRESULT hr = S_OK;
// Specify the path to the report you want to print
_bstr_t ReportPath("c:\\Program Files\\Business Objects\\Crystal Reports 11.5\\Samples\\En\\Reports\\General Business\\Inventory.rpt");
_variant_t vtEmpty(DISP_E_PARAMNOTFOUND, VT_ERROR);
// Instantiate the IApplication object
m_Application.CreateInstance("CrystalRuntime.Application.115");
//Open the Report using the OpenReport method
m_Report = m_Application->OpenReport(ReportPath, dummy)
//Print the Report to printer
m_Report->PrintOut(dummy, dummy, dummy, dummy);
Does it work? It should print the report with its 'default' printer settings and without prompting.
You wrote:
However, at the end of all this,
crystal reports still shows its own
printer selection dialog - but only
for some reports, it seems.
Generally speaking, I've found that Crystal tends to ignore commands to suppress dialogs if it thinks something is missing. I've found this to be true with the parameter dialog. Perhaps it apply to this situation as well. I would ask what is different about the reports that cause the dialog to be generated. There is a 'no printer' option that can be set. Perhaps this is the common thread.
Do you have access to the VB6 IDE? If you write the equivalent commands using VB6's interface, does the prompting occur?
You might also investigate using the CRPE32.dll instead of the report-designer control. To be honest, I don't know if the RDC wraps the CRPE DLL or is an entirely-separate code base.
Turns out it was a bug in my code after all - I'd previously put in a wrapper for the RDC API to fix certain other bugs we were having; due to the large number of methods in the IReport interfaces, I wrote a script to generate pass-through stubs for the methods I wasn't interested in. Turns out that script was passing in bogus values for parameters with default values. Oops! Fixing the wrapper code fixed the bug here.