FlatCAMApp.py 288 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import sys
  9. import traceback
  10. import urllib.request, urllib.parse, urllib.error
  11. import getopt
  12. import os
  13. import random
  14. import logging
  15. import simplejson as json
  16. import re
  17. import os
  18. from stat import S_IREAD, S_IRGRP, S_IROTH
  19. import subprocess
  20. import tkinter as tk
  21. from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport
  22. from PyQt5.QtCore import QSettings
  23. import time # Just used for debugging. Double check before removing.
  24. import urllib.request, urllib.parse, urllib.error
  25. import webbrowser
  26. from contextlib import contextmanager
  27. from xml.dom.minidom import parseString as parse_xml_string
  28. from copy import copy,deepcopy
  29. import numpy as np
  30. from datetime import datetime
  31. import gc
  32. ########################################
  33. ## Imports part of FlatCAM ##
  34. ########################################
  35. from ObjectCollection import *
  36. from FlatCAMObj import *
  37. from PlotCanvas import *
  38. from FlatCAMGUI import *
  39. from FlatCAMCommon import LoudDict
  40. from FlatCAMPostProc import load_postprocessors
  41. from FlatCAMEditor import FlatCAMGeoEditor, FlatCAMExcEditor
  42. from FlatCAMProcess import *
  43. from FlatCAMWorkerStack import WorkerStack
  44. from VisPyVisuals import Color
  45. from vispy.gloo.util import _screenshot
  46. from vispy.io import write_png
  47. from flatcamTools import *
  48. from multiprocessing import Pool
  49. import tclCommands
  50. # from ParseFont import *
  51. ########################################
  52. ## App ##
  53. ########################################
  54. class App(QtCore.QObject):
  55. """
  56. The main application class. The constructor starts the GUI.
  57. """
  58. # Get Cmd Line Options
  59. cmd_line_shellfile = ''
  60. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  61. try:
  62. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  63. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  64. except getopt.GetoptError:
  65. print(cmd_line_help)
  66. sys.exit(2)
  67. for opt, arg in cmd_line_options:
  68. if opt == '-h':
  69. print(cmd_line_help)
  70. sys.exit()
  71. elif opt == '--shellfile':
  72. cmd_line_shellfile = arg
  73. # Logging ##
  74. log = logging.getLogger('base')
  75. log.setLevel(logging.DEBUG)
  76. # log.setLevel(logging.WARNING)
  77. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  78. handler = logging.StreamHandler()
  79. handler.setFormatter(formatter)
  80. log.addHandler(handler)
  81. # Version
  82. version = 8.909
  83. version_date = "2019/02/13"
  84. beta = True
  85. # current date now
  86. date = str(datetime.today()).rpartition(' ')[0]
  87. # URL for update checks and statistics
  88. version_url = "http://flatcam.org/version"
  89. # App URL
  90. app_url = "http://flatcam.org"
  91. # Manual URL
  92. manual_url = "http://flatcam.org/manual/index.html"
  93. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  94. should_we_quit = True
  95. ##################
  96. ## Signals ##
  97. ##################
  98. # Inform the user
  99. # Handled by:
  100. # * App.info() --> Print on the status bar
  101. inform = QtCore.pyqtSignal(str)
  102. # General purpose background task
  103. worker_task = QtCore.pyqtSignal(dict)
  104. # File opened
  105. # Handled by:
  106. # * register_folder()
  107. # * register_recent()
  108. # Note: Setting the parameters to unicode does not seem
  109. # to have an effect. Then are received as Qstring
  110. # anyway.
  111. # File type and filename
  112. file_opened = QtCore.pyqtSignal(str, str)
  113. # File type and filename
  114. file_saved = QtCore.pyqtSignal(str, str)
  115. # Percentage of progress
  116. progress = QtCore.pyqtSignal(int)
  117. plots_updated = QtCore.pyqtSignal()
  118. # Emitted by new_object() and passes the new object as argument, plot flag.
  119. # on_object_created() adds the object to the collection, plots on appropriate flag
  120. # and emits new_object_available.
  121. object_created = QtCore.pyqtSignal(object, bool, bool)
  122. # Emitted when a object has been changed (like scaled, mirrored)
  123. object_changed = QtCore.pyqtSignal(object)
  124. # Emitted after object has been plotted.
  125. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  126. object_plotted = QtCore.pyqtSignal(object)
  127. # Emitted when a new object has been added to the collection
  128. # and is ready to be used.
  129. new_object_available = QtCore.pyqtSignal(object)
  130. message = QtCore.pyqtSignal(str, str, str)
  131. # Emmited when shell command is finished(one command only)
  132. shell_command_finished = QtCore.pyqtSignal(object)
  133. # Emitted when multiprocess pool has been recreated
  134. pool_recreated = QtCore.pyqtSignal(object)
  135. # Emitted when an unhandled exception happens
  136. # in the worker task.
  137. thread_exception = QtCore.pyqtSignal(object)
  138. def __init__(self, user_defaults=True, post_gui=None):
  139. """
  140. Starts the application.
  141. :return: app
  142. :rtype: App
  143. """
  144. App.log.info("FlatCAM Starting...")
  145. ###################
  146. ### OS-specific ###
  147. ###################
  148. # Folder for user settings.
  149. if sys.platform == 'win32':
  150. from win32com.shell import shell, shellcon
  151. if platform.architecture()[0] == '32bit':
  152. App.log.debug("Win32!")
  153. else:
  154. App.log.debug("Win64!")
  155. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + \
  156. '\FlatCAM'
  157. self.os = 'windows'
  158. else: # Linux/Unix/MacOS
  159. self.data_path = os.path.expanduser('~') + \
  160. '/.FlatCAM'
  161. self.os = 'unix'
  162. ###############################
  163. ### Setup folders and files ###
  164. ###############################
  165. if not os.path.exists(self.data_path):
  166. os.makedirs(self.data_path)
  167. App.log.debug('Created data folder: ' + self.data_path)
  168. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  169. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  170. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  171. if not os.path.exists(self.postprocessorpaths):
  172. os.makedirs(self.postprocessorpaths)
  173. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  174. # create current_defaults.FlatConfig file if there is none
  175. try:
  176. f = open(self.data_path + '/current_defaults.FlatConfig')
  177. f.close()
  178. except IOError:
  179. App.log.debug('Creating empty current_defaults.FlatConfig')
  180. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  181. json.dump({}, f)
  182. f.close()
  183. # create factory_defaults.FlatConfig file if there is none
  184. try:
  185. f = open(self.data_path + '/factory_defaults.FlatConfig')
  186. f.close()
  187. except IOError:
  188. App.log.debug('Creating empty factory_defaults.FlatConfig')
  189. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  190. json.dump({}, f)
  191. f.close()
  192. try:
  193. f = open(self.data_path + '/recent.json')
  194. f.close()
  195. except IOError:
  196. App.log.debug('Creating empty recent.json')
  197. f = open(self.data_path + '/recent.json', 'w')
  198. json.dump([], f)
  199. f.close()
  200. # Application directory. CHDIR to it. Otherwise, trying to load
  201. # GUI icons will fail as their path is relative.
  202. # This will fail under cx_freeze ...
  203. self.app_home = os.path.dirname(os.path.realpath(__file__))
  204. App.log.debug("Application path is " + self.app_home)
  205. App.log.debug("Started in " + os.getcwd())
  206. # cx_freeze workaround
  207. if os.path.isfile(self.app_home):
  208. self.app_home = os.path.dirname(self.app_home)
  209. os.chdir(self.app_home)
  210. # Create multiprocessing pool
  211. self.pool = Pool()
  212. # variable to store mouse coordinates
  213. self.mouse = [0, 0]
  214. ####################
  215. ## Initialize GUI ##
  216. ####################
  217. # FlatCAM colors used in plotting
  218. self.FC_light_green = '#BBF268BF'
  219. self.FC_dark_green = '#006E20BF'
  220. self.FC_light_blue = '#a5a5ffbf'
  221. self.FC_dark_blue = '#0000ffbf'
  222. QtCore.QObject.__init__(self)
  223. self.ui = FlatCAMGUI(self.version, self.beta, self)
  224. # self.connect(self.ui,
  225. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  226. # self.save_geometry) PyQt4
  227. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  228. self.ui.final_save.connect(self.final_save)
  229. ##############
  230. #### Data ####
  231. ##############
  232. self.recent = []
  233. self.clipboard = QtWidgets.QApplication.clipboard()
  234. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  235. self.project_filename = None
  236. self.toggle_units_ignore = False
  237. # self.defaults_form = PreferencesUI()
  238. self.general_defaults_form = GeneralPreferencesUI()
  239. self.gerber_defaults_form = GerberPreferencesUI()
  240. self.excellon_defaults_form = ExcellonPreferencesUI()
  241. self.geometry_defaults_form = GeometryPreferencesUI()
  242. self.cncjob_defaults_form = CNCJobPreferencesUI()
  243. self.tools_defaults_form = ToolsPreferencesUI()
  244. # when adding entries here read the comments in the method found bellow named:
  245. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  246. self.defaults_form_fields = {
  247. "units": self.general_defaults_form.general_app_group.units_radio,
  248. "global_shell_at_startup": self.general_defaults_form.general_app_group.shell_startup_cb,
  249. "global_version_check": self.general_defaults_form.general_app_group.version_check_cb,
  250. "global_send_stats": self.general_defaults_form.general_app_group.send_stats_cb,
  251. "global_gridx": self.general_defaults_form.general_gui_group.gridx_entry,
  252. "global_gridy": self.general_defaults_form.general_gui_group.gridy_entry,
  253. "global_snap_max": self.general_defaults_form.general_gui_group.snap_max_dist_entry,
  254. "global_plot_fill": self.general_defaults_form.general_gui_group.pf_color_entry,
  255. "global_plot_line": self.general_defaults_form.general_gui_group.pl_color_entry,
  256. "global_sel_fill": self.general_defaults_form.general_gui_group.sf_color_entry,
  257. "global_sel_line": self.general_defaults_form.general_gui_group.sl_color_entry,
  258. "global_alt_sel_fill": self.general_defaults_form.general_gui_group.alt_sf_color_entry,
  259. "global_alt_sel_line": self.general_defaults_form.general_gui_group.alt_sl_color_entry,
  260. "global_draw_color": self.general_defaults_form.general_gui_group.draw_color_entry,
  261. "global_sel_draw_color": self.general_defaults_form.general_gui_group.sel_draw_color_entry,
  262. "global_pan_button": self.general_defaults_form.general_app_group.pan_button_radio,
  263. "global_mselect_key": self.general_defaults_form.general_app_group.mselect_radio,
  264. # "global_pan_with_space_key": self.general_defaults_form.general_gui_group.pan_with_space_cb,
  265. "global_workspace": self.general_defaults_form.general_gui_group.workspace_cb,
  266. "global_workspaceT": self.general_defaults_form.general_gui_group.wk_cb,
  267. "gerber_plot": self.gerber_defaults_form.gerber_gen_group.plot_cb,
  268. "gerber_solid": self.gerber_defaults_form.gerber_gen_group.solid_cb,
  269. "gerber_multicolored": self.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  270. "gerber_circle_steps": self.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  271. "gerber_isotooldia": self.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  272. "gerber_isopasses": self.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  273. "gerber_isooverlap": self.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  274. "gerber_combine_passes": self.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  275. "gerber_milling_type": self.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  276. "gerber_noncoppermargin": self.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  277. "gerber_noncopperrounded": self.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  278. "gerber_bboxmargin": self.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  279. "gerber_bboxrounded": self.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  280. "excellon_plot": self.excellon_defaults_form.excellon_gen_group.plot_cb,
  281. "excellon_solid": self.excellon_defaults_form.excellon_gen_group.solid_cb,
  282. "excellon_format_upper_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  283. "excellon_format_lower_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  284. "excellon_format_upper_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  285. "excellon_format_lower_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  286. "excellon_zeros": self.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  287. "excellon_units": self.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  288. "excellon_optimization_type": self.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  289. "excellon_search_time": self.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  290. "excellon_drillz": self.excellon_defaults_form.excellon_opt_group.cutz_entry,
  291. "excellon_travelz": self.excellon_defaults_form.excellon_opt_group.travelz_entry,
  292. "excellon_feedrate": self.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  293. "excellon_feedrate_rapid": self.excellon_defaults_form.excellon_opt_group.feedrate_rapid_entry,
  294. "excellon_feedrate_probe": self.excellon_defaults_form.excellon_opt_group.feedrate_probe_entry,
  295. "excellon_spindlespeed": self.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  296. "excellon_dwell": self.excellon_defaults_form.excellon_opt_group.dwell_cb,
  297. "excellon_dwelltime": self.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  298. "excellon_toolchange": self.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  299. "excellon_toolchangez": self.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  300. "excellon_toolchangexy": self.excellon_defaults_form.excellon_opt_group.toolchangexy_entry,
  301. "excellon_ppname_e": self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  302. "excellon_z_pdepth": self.excellon_defaults_form.excellon_opt_group.pdepth_entry,
  303. "excellon_f_plunge": self.excellon_defaults_form.excellon_opt_group.fplunge_cb,
  304. "excellon_startz": self.excellon_defaults_form.excellon_opt_group.estartz_entry,
  305. "excellon_endz": self.excellon_defaults_form.excellon_opt_group.eendz_entry,
  306. "excellon_tooldia": self.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  307. "excellon_offset": self.excellon_defaults_form.excellon_opt_group.offset_entry,
  308. "excellon_slot_tooldia": self.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  309. "excellon_gcode_type": self.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  310. "geometry_plot": self.geometry_defaults_form.geometry_gen_group.plot_cb,
  311. "geometry_cnctooldia": self.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  312. "geometry_circle_steps": self.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  313. "geometry_segx": self.geometry_defaults_form.geometry_opt_group.segx_entry,
  314. "geometry_segy": self.geometry_defaults_form.geometry_opt_group.segy_entry,
  315. "geometry_cutz": self.geometry_defaults_form.geometry_opt_group.cutz_entry,
  316. "geometry_travelz": self.geometry_defaults_form.geometry_opt_group.travelz_entry,
  317. "geometry_feedrate": self.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  318. "geometry_feedrate_z": self.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  319. "geometry_feedrate_rapid": self.geometry_defaults_form.geometry_opt_group.cncfeedrate_rapid_entry,
  320. "geometry_feedrate_probe": self.geometry_defaults_form.geometry_opt_group.feedrate_probe_entry,
  321. "geometry_spindlespeed": self.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  322. "geometry_dwell": self.geometry_defaults_form.geometry_opt_group.dwell_cb,
  323. "geometry_dwelltime": self.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  324. "geometry_ppname_g": self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  325. "geometry_z_pdepth": self.geometry_defaults_form.geometry_opt_group.pdepth_entry,
  326. "geometry_f_plunge": self.geometry_defaults_form.geometry_opt_group.fplunge_cb,
  327. "geometry_toolchange": self.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  328. "geometry_toolchangez": self.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  329. "geometry_toolchangexy": self.geometry_defaults_form.geometry_opt_group.toolchangexy_entry,
  330. "geometry_startz": self.geometry_defaults_form.geometry_opt_group.gstartz_entry,
  331. "geometry_endz": self.geometry_defaults_form.geometry_opt_group.gendz_entry,
  332. "geometry_multidepth": self.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  333. "geometry_depthperpass": self.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  334. "geometry_extracut": self.geometry_defaults_form.geometry_opt_group.extracut_cb,
  335. "cncjob_plot": self.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  336. "cncjob_plot_kind": self.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  337. "cncjob_tooldia": self.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  338. "cncjob_coords_decimals": self.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  339. "cncjob_fr_decimals": self.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  340. "cncjob_steps_per_circle": self.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  341. "cncjob_prepend": self.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  342. "cncjob_append": self.cncjob_defaults_form.cncjob_opt_group.append_text,
  343. "tools_ncctools": self.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  344. "tools_nccoverlap": self.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  345. "tools_nccmargin": self.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  346. "tools_nccmethod": self.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  347. "tools_nccconnect": self.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  348. "tools_ncccontour": self.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  349. "tools_nccrest": self.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  350. "tools_cutouttooldia": self.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  351. "tools_cutoutmargin": self.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  352. "tools_cutoutgapsize": self.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  353. "tools_gaps_rect": self.tools_defaults_form.tools_cutout_group.gaps_radio,
  354. "tools_gaps_ff": self.tools_defaults_form.tools_cutout_group.gaps_combo,
  355. "tools_painttooldia": self.tools_defaults_form.tools_paint_group.painttooldia_entry,
  356. "tools_paintoverlap": self.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  357. "tools_paintmargin": self.tools_defaults_form.tools_paint_group.paintmargin_entry,
  358. "tools_paintmethod": self.tools_defaults_form.tools_paint_group.paintmethod_combo,
  359. "tools_selectmethod": self.tools_defaults_form.tools_paint_group.selectmethod_combo,
  360. "tools_pathconnect": self.tools_defaults_form.tools_paint_group.pathconnect_cb,
  361. "tools_paintcontour": self.tools_defaults_form.tools_paint_group.contour_cb,
  362. "tools_2sided_mirror_axis": self.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  363. "tools_2sided_axis_loc": self.tools_defaults_form.tools_2sided_group.axis_location_radio,
  364. "tools_2sided_drilldia": self.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  365. "tools_film_type": self.tools_defaults_form.tools_film_group.film_type_radio,
  366. "tools_film_boundary": self.tools_defaults_form.tools_film_group.film_boundary_entry,
  367. "tools_film_scale": self.tools_defaults_form.tools_film_group.film_scale_entry,
  368. "tools_panelize_spacing_columns": self.tools_defaults_form.tools_panelize_group.pspacing_columns,
  369. "tools_panelize_spacing_rows": self.tools_defaults_form.tools_panelize_group.pspacing_rows,
  370. "tools_panelize_columns": self.tools_defaults_form.tools_panelize_group.pcolumns,
  371. "tools_panelize_rows": self.tools_defaults_form.tools_panelize_group.prows,
  372. "tools_panelize_constrain": self.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  373. "tools_panelize_constrainx": self.tools_defaults_form.tools_panelize_group.px_width_entry,
  374. "tools_panelize_constrainy": self.tools_defaults_form.tools_panelize_group.py_height_entry,
  375. "tools_calc_vshape_tip_dia": self.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  376. "tools_calc_vshape_tip_angle": self.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  377. "tools_calc_vshape_cut_z": self.tools_defaults_form.tools_calculators_group.cut_z_entry,
  378. "tools_calc_electro_length": self.tools_defaults_form.tools_calculators_group.pcblength_entry,
  379. "tools_calc_electro_width": self.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  380. "tools_calc_electro_cdensity": self.tools_defaults_form.tools_calculators_group.cdensity_entry,
  381. "tools_calc_electro_growth": self.tools_defaults_form.tools_calculators_group.growth_entry
  382. }
  383. # loads postprocessors
  384. self.postprocessors = load_postprocessors(self)
  385. for name in list(self.postprocessors.keys()):
  386. self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  387. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  388. if name == 'hpgl':
  389. continue
  390. self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  391. self.defaults = LoudDict()
  392. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  393. self.defaults.update({
  394. "global_serial": 0,
  395. "global_stats": {},
  396. "units": "IN",
  397. "global_version_check": True,
  398. "global_send_stats": True,
  399. "global_gridx": 1.0,
  400. "global_gridy": 1.0,
  401. "global_snap_max": 0.05,
  402. "global_plot_fill": '#BBF268BF',
  403. "global_plot_line": '#006E20BF',
  404. "global_sel_fill": '#a5a5ffbf',
  405. "global_sel_line": '#0000ffbf',
  406. "global_alt_sel_fill": '#BBF268BF',
  407. "global_alt_sel_line": '#006E20BF',
  408. "global_draw_color": '#FF0000',
  409. "global_sel_draw_color": '#0000FF',
  410. "global_pan_button": '2',
  411. "global_mselect_key": 'Control',
  412. # "global_pan_with_space_key": False,
  413. "global_workspace": False,
  414. "global_workspaceT": "A4P",
  415. "global_toolbar_view": 127,
  416. "global_background_timeout": 300000, # Default value is 5 minutes
  417. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  418. # (python trace only for unknown errors),
  419. # 1 = show trace(show trace allways),
  420. # 2 = (For the future).
  421. # Persistence
  422. "global_last_folder": None,
  423. "global_last_save_folder": None,
  424. # Default window geometry
  425. "global_def_win_x": 100,
  426. "global_def_win_y": 100,
  427. "global_def_win_w": 1024,
  428. "global_def_win_h": 650,
  429. # Constants...
  430. "global_defaults_save_period_ms": 20000, # Time between default saves.
  431. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  432. "global_shell_at_startup": False, # Show the shell at startup.
  433. "global_recent_limit": 10, # Max. items in recent list.
  434. "fit_key": 'V',
  435. "zoom_out_key": '-',
  436. "zoom_in_key": '=',
  437. "grid_toggle_key": 'G',
  438. "zoom_ratio": 1.5,
  439. "global_point_clipboard_format": "(%.4f, %.4f)",
  440. "global_zdownrate": None,
  441. "gerber_plot": True,
  442. "gerber_solid": True,
  443. "gerber_multicolored": False,
  444. "gerber_isotooldia": 0.016,
  445. "gerber_isopasses": 1,
  446. "gerber_isooverlap": 0.15,
  447. "gerber_combine_passes": False,
  448. "gerber_milling_type": "cl",
  449. "gerber_noncoppermargin": 0.1,
  450. "gerber_noncopperrounded": False,
  451. "gerber_bboxmargin": 0.1,
  452. "gerber_bboxrounded": False,
  453. "gerber_circle_steps": 64,
  454. "gerber_use_buffer_for_union": True,
  455. "excellon_plot": True,
  456. "excellon_solid": True,
  457. "excellon_format_upper_in": 2,
  458. "excellon_format_lower_in": 4,
  459. "excellon_format_upper_mm": 3,
  460. "excellon_format_lower_mm": 3,
  461. "excellon_zeros": "L",
  462. "excellon_units": "INCH",
  463. "excellon_optimization_type": 'B',
  464. "excellon_search_time": 3,
  465. "excellon_drillz": -0.1,
  466. "excellon_travelz": 0.1,
  467. "excellon_feedrate": 3.0,
  468. "excellon_feedrate_rapid": 3.0,
  469. "excellon_feedrate_probe": 3.0,
  470. "excellon_spindlespeed": None,
  471. "excellon_dwell": False,
  472. "excellon_dwelltime": 1,
  473. "excellon_toolchange": False,
  474. "excellon_toolchangez": 1.0,
  475. "excellon_toolchangexy": "0.0, 0.0",
  476. "excellon_tooldia": 0.016,
  477. "excellon_offset": 0.0,
  478. "excellon_slot_tooldia": 0.016,
  479. "excellon_startz": None,
  480. "excellon_endz": 2.0,
  481. "excellon_ppname_e": 'default',
  482. "excellon_z_pdepth": -0.02,
  483. "excellon_f_plunge": False,
  484. "excellon_gcode_type": "drills",
  485. "geometry_plot": True,
  486. "geometry_segx": 0.0,
  487. "geometry_segy": 0.0,
  488. "geometry_cutz": -0.002,
  489. "geometry_travelz": 0.1,
  490. "geometry_toolchange": False,
  491. "geometry_toolchangez": 1.0,
  492. "geometry_toolchangexy": "0.0, 0.0",
  493. "geometry_startz": None,
  494. "geometry_endz": 2.0,
  495. "geometry_feedrate": 3.0,
  496. "geometry_feedrate_z": 3.0,
  497. "geometry_feedrate_rapid": 3.0,
  498. "geometry_feedrate_probe": 3.0,
  499. "geometry_cnctooldia": 0.016,
  500. "geometry_spindlespeed": None,
  501. "geometry_dwell": False,
  502. "geometry_dwelltime": 1,
  503. "geometry_ppname_g": 'default',
  504. "geometry_z_pdepth": -0.02,
  505. "geometry_f_plunge": False,
  506. "geometry_depthperpass": 0.002,
  507. "geometry_multidepth": False,
  508. "geometry_extracut": False,
  509. "geometry_circle_steps": 64,
  510. "cncjob_plot": True,
  511. "cncjob_plot_kind": 'all',
  512. "cncjob_tooldia": 0.0393701,
  513. "cncjob_coords_decimals": 4,
  514. "cncjob_fr_decimals": 2,
  515. "cncjob_prepend": "",
  516. "cncjob_append": "",
  517. "cncjob_steps_per_circle": 64,
  518. "tools_ncctools": "1.0, 0.5",
  519. "tools_nccoverlap": 0.4,
  520. "tools_nccmargin": 0.1,
  521. "tools_nccmethod": "seed",
  522. "tools_nccconnect": True,
  523. "tools_ncccontour": True,
  524. "tools_nccrest": False,
  525. "tools_cutouttooldia": 0.1,
  526. "tools_cutoutmargin": 0.1,
  527. "tools_cutoutgapsize": 0.15,
  528. "tools_gaps_rect": "4",
  529. "tools_gaps_ff": "8",
  530. "tools_painttooldia": 0.07,
  531. "tools_paintoverlap": 0.15,
  532. "tools_paintmargin": 0.0,
  533. "tools_paintmethod": "seed",
  534. "tools_selectmethod": "single",
  535. "tools_pathconnect": True,
  536. "tools_paintcontour": True,
  537. "tools_2sided_mirror_axis": "X",
  538. "tools_2sided_axis_loc": "point",
  539. "tools_2sided_drilldia": 1,
  540. "tools_film_type": 'neg',
  541. "tools_film_boundary": 1,
  542. "tools_film_scale": 0,
  543. "tools_panelize_spacing_columns": 0,
  544. "tools_panelize_spacing_rows": 0,
  545. "tools_panelize_columns": 1,
  546. "tools_panelize_rows": 1,
  547. "tools_panelize_constrain": False,
  548. "tools_panelize_constrainx": 0.0,
  549. "tools_panelize_constrainy": 0.0,
  550. "tools_calc_vshape_tip_dia": 0.007874,
  551. "tools_calc_vshape_tip_angle": 30,
  552. "tools_calc_vshape_cut_z": 0.000787,
  553. "tools_calc_electro_length": 10.0,
  554. "tools_calc_electro_width": 10.0,
  555. "tools_calc_electro_cdensity":13.0,
  556. "tools_calc_electro_growth": 10.0
  557. })
  558. ###############################
  559. ### Load defaults from file ###
  560. if user_defaults:
  561. self.load_defaults(filename='current_defaults')
  562. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  563. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  564. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  565. self.save_defaults(silent=True)
  566. self.propagate_defaults(silent=True)
  567. self.restore_main_win_geom()
  568. def auto_save_defaults():
  569. try:
  570. self.save_defaults(silent=True)
  571. self.propagate_defaults(silent=True)
  572. finally:
  573. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  574. # the following lines activates automatic defaults save
  575. # if user_defaults:
  576. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  577. # self.options_form = PreferencesUI()
  578. self.general_options_form = GeneralPreferencesUI()
  579. self.gerber_options_form = GerberPreferencesUI()
  580. self.excellon_options_form = ExcellonPreferencesUI()
  581. self.geometry_options_form = GeometryPreferencesUI()
  582. self.cncjob_options_form = CNCJobPreferencesUI()
  583. self.tools_options_form = ToolsPreferencesUI()
  584. self.options_form_fields = {
  585. "units": self.general_options_form.general_app_group.units_radio,
  586. "global_gridx": self.general_options_form.general_gui_group.gridx_entry,
  587. "global_gridy": self.general_options_form.general_gui_group.gridy_entry,
  588. "global_snap_max": self.general_options_form.general_gui_group.snap_max_dist_entry,
  589. "gerber_plot": self.gerber_options_form.gerber_gen_group.plot_cb,
  590. "gerber_solid": self.gerber_options_form.gerber_gen_group.solid_cb,
  591. "gerber_multicolored": self.gerber_options_form.gerber_gen_group.multicolored_cb,
  592. "gerber_isotooldia": self.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  593. "gerber_isopasses": self.gerber_options_form.gerber_opt_group.iso_width_entry,
  594. "gerber_isooverlap": self.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  595. "gerber_combine_passes": self.gerber_options_form.gerber_opt_group.combine_passes_cb,
  596. "gerber_noncoppermargin": self.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  597. "gerber_noncopperrounded": self.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  598. "gerber_bboxmargin": self.gerber_options_form.gerber_opt_group.bbmargin_entry,
  599. "gerber_bboxrounded": self.gerber_options_form.gerber_opt_group.bbrounded_cb,
  600. "excellon_plot": self.excellon_options_form.excellon_gen_group.plot_cb,
  601. "excellon_solid": self.excellon_options_form.excellon_gen_group.solid_cb,
  602. "excellon_format_upper_in": self.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  603. "excellon_format_lower_in": self.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  604. "excellon_format_upper_mm": self.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  605. "excellon_format_lower_mm": self.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  606. "excellon_zeros": self.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  607. "excellon_units": self.excellon_options_form.excellon_gen_group.excellon_units_radio,
  608. "excellon_optimization_type": self.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  609. "excellon_drillz": self.excellon_options_form.excellon_opt_group.cutz_entry,
  610. "excellon_travelz": self.excellon_options_form.excellon_opt_group.travelz_entry,
  611. "excellon_feedrate": self.excellon_options_form.excellon_opt_group.feedrate_entry,
  612. "excellon_feedrate_rapid": self.excellon_options_form.excellon_opt_group.feedrate_rapid_entry,
  613. "excellon_spindlespeed": self.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  614. "excellon_dwell": self.excellon_options_form.excellon_opt_group.dwell_cb,
  615. "excellon_dwelltime": self.excellon_options_form.excellon_opt_group.dwelltime_entry,
  616. "excellon_toolchange": self.excellon_options_form.excellon_opt_group.toolchange_cb,
  617. "excellon_toolchangez": self.excellon_options_form.excellon_opt_group.toolchangez_entry,
  618. "excellon_toolchangexy": self.excellon_options_form.excellon_opt_group.toolchangexy_entry,
  619. "excellon_tooldia": self.excellon_options_form.excellon_opt_group.tooldia_entry,
  620. "excellon_ppname_e": self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  621. "excellon_f_plunge": self.excellon_options_form.excellon_opt_group.fplunge_cb,
  622. "excellon_startz": self.excellon_options_form.excellon_opt_group.estartz_entry,
  623. "excellon_endz": self.excellon_options_form.excellon_opt_group.eendz_entry,
  624. "geometry_plot": self.geometry_options_form.geometry_gen_group.plot_cb,
  625. "geometry_cnctooldia": self.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  626. "geometry_segx": self.geometry_options_form.geometry_opt_group.segx_entry,
  627. "geometry_segy": self.geometry_options_form.geometry_opt_group.segy_entry,
  628. "geometry_cutz": self.geometry_options_form.geometry_opt_group.cutz_entry,
  629. "geometry_travelz": self.geometry_options_form.geometry_opt_group.travelz_entry,
  630. "geometry_feedrate": self.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  631. "geometry_feedrate_z": self.geometry_options_form.geometry_opt_group.cncplunge_entry,
  632. "geometry_feedrate_rapid": self.geometry_options_form.geometry_opt_group.cncfeedrate_rapid_entry,
  633. "geometry_spindlespeed": self.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  634. "geometry_dwell": self.geometry_options_form.geometry_opt_group.dwell_cb,
  635. "geometry_dwelltime": self.geometry_options_form.geometry_opt_group.dwelltime_entry,
  636. "geometry_ppname_g": self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  637. "geometry_f_plunge": self.geometry_options_form.geometry_opt_group.fplunge_cb,
  638. "geometry_toolchange": self.geometry_options_form.geometry_opt_group.toolchange_cb,
  639. "geometry_toolchangez": self.geometry_options_form.geometry_opt_group.toolchangez_entry,
  640. "geometry_toolchangexy": self.geometry_options_form.geometry_opt_group.toolchangexy_entry,
  641. "geometry_startz": self.geometry_options_form.geometry_opt_group.gstartz_entry,
  642. "geometry_endz": self.geometry_options_form.geometry_opt_group.gendz_entry,
  643. "geometry_depthperpass": self.geometry_options_form.geometry_opt_group.depthperpass_entry,
  644. "geometry_multidepth": self.geometry_options_form.geometry_opt_group.multidepth_cb,
  645. "geometry_extracut": self.geometry_options_form.geometry_opt_group.extracut_cb,
  646. "cncjob_plot": self.cncjob_options_form.cncjob_gen_group.plot_cb,
  647. "cncjob_tooldia": self.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  648. "cncjob_prepend": self.cncjob_options_form.cncjob_opt_group.prepend_text,
  649. "cncjob_append": self.cncjob_options_form.cncjob_opt_group.append_text,
  650. "tools_ncctools": self.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  651. "tools_nccoverlap": self.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  652. "tools_nccmargin": self.tools_options_form.tools_ncc_group.ncc_margin_entry,
  653. "tools_cutouttooldia": self.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  654. "tools_cutoutmargin": self.tools_options_form.tools_cutout_group.cutout_margin_entry,
  655. "tools_cutoutgapsize": self.tools_options_form.tools_cutout_group.cutout_gap_entry,
  656. "tools_gaps_rect": self.tools_options_form.tools_cutout_group.gaps_radio,
  657. "tools_gaps_ff": self.tools_options_form.tools_cutout_group.gaps_combo,
  658. "tools_painttooldia": self.tools_options_form.tools_paint_group.painttooldia_entry,
  659. "tools_paintoverlap": self.tools_options_form.tools_paint_group.paintoverlap_entry,
  660. "tools_paintmargin": self.tools_options_form.tools_paint_group.paintmargin_entry,
  661. "tools_paintmethod": self.tools_options_form.tools_paint_group.paintmethod_combo,
  662. "tools_selectmethod": self.tools_options_form.tools_paint_group.selectmethod_combo,
  663. "tools_pathconnect": self.tools_options_form.tools_paint_group.pathconnect_cb,
  664. "tools_paintcontour": self.tools_options_form.tools_paint_group.contour_cb,
  665. "tools_2sided_mirror_axis": self.tools_options_form.tools_2sided_group.mirror_axis_radio,
  666. "tools_2sided_axis_loc": self.tools_options_form.tools_2sided_group.axis_location_radio,
  667. "tools_2sided_drilldia": self.tools_options_form.tools_2sided_group.drill_dia_entry,
  668. "tools_film_type": self.tools_options_form.tools_film_group.film_type_radio,
  669. "tools_film_boundary": self.tools_options_form.tools_film_group.film_boundary_entry,
  670. "tools_film_scale": self.tools_options_form.tools_film_group.film_scale_entry,
  671. "tools_panelize_spacing_columns": self.tools_options_form.tools_panelize_group.pspacing_columns,
  672. "tools_panelize_spacing_rows": self.tools_options_form.tools_panelize_group.pspacing_rows,
  673. "tools_panelize_columns": self.tools_options_form.tools_panelize_group.pcolumns,
  674. "tools_panelize_rows": self.tools_options_form.tools_panelize_group.prows,
  675. "tools_panelize_constrain": self.tools_options_form.tools_panelize_group.pconstrain_cb,
  676. "tools_panelize_constrainx": self.tools_options_form.tools_panelize_group.px_width_entry,
  677. "tools_panelize_constrainy": self.tools_options_form.tools_panelize_group.py_height_entry
  678. }
  679. for name in list(self.postprocessors.keys()):
  680. self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  681. self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  682. self.options = LoudDict()
  683. self.options.set_change_callback(self.on_options_dict_change)
  684. self.options.update({
  685. "units": "IN",
  686. "global_gridx": 1.0,
  687. "global_gridy": 1.0,
  688. "global_snap_max": 0.05,
  689. "global_background_timeout": 300000, # Default value is 5 minutes
  690. "global_verbose_error_level": 0, # Shell verbosity:
  691. # 0 = default(python trace only for unknown errors),
  692. # 1 = show trace(show trace allways), 2 = (For the future).
  693. "gerber_plot": True,
  694. "gerber_solid": True,
  695. "gerber_multicolored": False,
  696. "gerber_isotooldia": 0.016,
  697. "gerber_isopasses": 1,
  698. "gerber_isooverlap": 0.15,
  699. "gerber_combine_passes": True,
  700. "gerber_noncoppermargin": 0.0,
  701. "gerber_noncopperrounded": False,
  702. "gerber_bboxmargin": 0.0,
  703. "gerber_bboxrounded": False,
  704. "excellon_plot": True,
  705. "excellon_solid": False,
  706. "excellon_format_upper_in": 2,
  707. "excellon_format_lower_in": 4,
  708. "excellon_format_upper_mm": 3,
  709. "excellon_format_lower_mm": 3,
  710. "excellon_units": 'INCH',
  711. "excellon_optimization_type": 'B',
  712. "excellon_search_time": 3,
  713. "excellon_zeros": "L",
  714. "excellon_drillz": -0.1,
  715. "excellon_travelz": 0.1,
  716. "excellon_feedrate": 3.0,
  717. "excellon_feedrate_rapid": 3.0,
  718. "excellon_spindlespeed": None,
  719. "excellon_dwell": True,
  720. "excellon_dwelltime": 1000,
  721. "excellon_toolchange": False,
  722. "excellon_toolchangez": 1.0,
  723. "excellon_toolchangexy": "0.0, 0.0",
  724. "excellon_tooldia": 0.016,
  725. "excellon_ppname_e": 'default',
  726. "excellon_f_plunge": False,
  727. "excellon_startz": None,
  728. "excellon_endz": 2.0,
  729. "geometry_plot": True,
  730. "geometry_segx": 0.0,
  731. "geometry_segy": 0.0,
  732. "geometry_cutz": -0.002,
  733. "geometry_travelz": 0.1,
  734. "geometry_feedrate": 3.0,
  735. "geometry_feedrate_z": 3.0,
  736. "geometry_feedrate_rapid": 3.0,
  737. "geometry_spindlespeed": None,
  738. "geometry_dwell": True,
  739. "geometry_dwelltime": 1000,
  740. "geometry_cnctooldia": 0.016,
  741. "geometry_toolchange": False,
  742. "geometry_toolchangez": 2.0,
  743. "geometry_toolchangexy": "0.0, 0.0",
  744. "geometry_startz": None,
  745. "geometry_endz": 2.0,
  746. "geometry_ppname_g": "default",
  747. "geometry_f_plunge": False,
  748. "geometry_depthperpass": 0.002,
  749. "geometry_multidepth": False,
  750. "geometry_extracut": False,
  751. "cncjob_plot": True,
  752. "cncjob_tooldia": 0.016,
  753. "cncjob_prepend": "",
  754. "cncjob_append": "",
  755. "tools_ncctools": "1.0, 0.5",
  756. "tools_nccoverlap": 0.4,
  757. "tools_nccmargin": 1,
  758. "tools_cutouttooldia": 0.07,
  759. "tools_cutoutmargin": 0.1,
  760. "tools_cutoutgapsize": 0.15,
  761. "tools_gaps_rect": "4",
  762. "tools_gaps_ff": "8",
  763. "tools_painttooldia": 0.07,
  764. "tools_paintoverlap": 0.15,
  765. "tools_paintmargin": 0.0,
  766. "tools_paintmethod": "seed",
  767. "tools_selectmethod": "single",
  768. "tools_pathconnect": True,
  769. "tools_paintcontour": True,
  770. "tools_2sided_mirror_axis": "X",
  771. "tools_2sided_axis_loc": 'point',
  772. "tools_2sided_drilldia": 1,
  773. "tools_film_type": 'neg',
  774. "tools_film_boundary": 1,
  775. "tools_film_scale": 0,
  776. "tools_panelize_spacing_columns": 0,
  777. "tools_panelize_spacing_rows": 0,
  778. "tools_panelize_columns": 1,
  779. "tools_panelize_rows": 1,
  780. "tools_panelize_constrain": False,
  781. "tools_panelize_constrainx": 0.0,
  782. "tools_panelize_constrainy": 0.0
  783. })
  784. self.options.update(self.defaults) # Copy app defaults to project options
  785. self.gen_form = None
  786. self.ger_form = None
  787. self.exc_form = None
  788. self.geo_form = None
  789. self.cnc_form = None
  790. self.tools_form = None
  791. self.on_options_combo_change(0) # Will show the initial form
  792. ### Define OBJECT COLLECTION ###
  793. self.collection = ObjectCollection(self)
  794. self.ui.project_tab_layout.addWidget(self.collection.view)
  795. ###
  796. self.log.debug("Finished creating Object Collection.")
  797. ### Initialize the color box's color in Preferences -> Global -> Color
  798. # Init Plot Colors
  799. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  800. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  801. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  802. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  803. int(self.defaults['global_plot_fill'][7:9], 16))
  804. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  805. int(self.defaults['global_plot_fill'][7:9], 16))
  806. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  807. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  808. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  809. # Init Left-Right Selection colors
  810. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  811. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  812. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  813. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  814. int(self.defaults['global_sel_fill'][7:9], 16))
  815. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  816. int(self.defaults['global_sel_fill'][7:9], 16))
  817. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  818. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  819. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  820. # Init Right-Left Selection colors
  821. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(self.defaults['global_alt_sel_fill'])
  822. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  823. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  824. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  825. int(self.defaults['global_sel_fill'][7:9], 16))
  826. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  827. int(self.defaults['global_sel_fill'][7:9], 16))
  828. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(self.defaults['global_alt_sel_line'])
  829. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  830. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  831. # Init Draw color and Selection Draw Color
  832. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(self.defaults['global_draw_color'])
  833. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  834. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  835. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(self.defaults['global_sel_draw_color'])
  836. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  837. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  838. #### End of Data ####
  839. #### Plot Area ####
  840. start_plot_time = time.time() # debug
  841. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  842. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  843. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  844. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  845. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  846. # Keys over plot enabled
  847. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  848. self.ui.splitter.setStretchFactor(1, 2)
  849. # So it can receive key presses
  850. self.plotcanvas.vispy_canvas.native.setFocus()
  851. self.app_cursor = self.plotcanvas.new_cursor()
  852. self.app_cursor.enabled = False
  853. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  854. # depending on from where those tools are called different actions can be done
  855. self.call_source = 'app'
  856. end_plot_time = time.time()
  857. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  858. ### EDITOR section
  859. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  860. self.exc_editor = FlatCAMExcEditor(self)
  861. #### Adjust tabs width ####
  862. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  863. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  864. self.collection.view.setMinimumWidth(290)
  865. self.log.debug("Finished adding Geometry and Excellon Editor's.")
  866. #### Worker ####
  867. self.workers = WorkerStack()
  868. self.worker_task.connect(self.workers.add_task)
  869. ### Signal handling ###
  870. ## Custom signals
  871. self.inform.connect(self.info)
  872. self.message.connect(self.message_dialog)
  873. self.progress.connect(self.set_progress_bar)
  874. self.object_created.connect(self.on_object_created)
  875. self.object_changed.connect(self.on_object_changed)
  876. self.object_plotted.connect(self.on_object_plotted)
  877. self.plots_updated.connect(self.on_plots_updated)
  878. self.file_opened.connect(self.register_recent)
  879. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  880. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  881. ## Standard signals
  882. # Menu
  883. self.ui.menufilenew.triggered.connect(self.on_file_new_click)
  884. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  885. self.ui.menufileopengerber_follow.triggered.connect(self.on_fileopengerber_follow)
  886. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  887. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  888. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  889. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  890. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  891. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  892. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  893. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  894. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  895. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  896. self.ui.menufileexportexcellon.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=None))
  897. self.ui.menufileexportexcellon_altium.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=True))
  898. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  899. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  900. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  901. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  902. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  903. self.ui.menufile_exit.triggered.connect(self.on_app_exit)
  904. self.ui.menueditnew.triggered.connect(self.new_geometry_object)
  905. self.ui.menueditnewexc.triggered.connect(self.new_excellon_object)
  906. self.ui.menueditedit.triggered.connect(self.object2editor)
  907. self.ui.menueditok.triggered.connect(self.editor2object)
  908. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  909. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  910. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  911. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  912. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  913. self.ui.menueditdelete.triggered.connect(self.on_delete)
  914. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  915. self.ui.menueditcopyobjectasgeom.triggered.connect(self.on_copy_object_as_geometry)
  916. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  917. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  918. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  919. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  920. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  921. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  922. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  923. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  924. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  925. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  926. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  927. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  928. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  929. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  930. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  931. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  932. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  933. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  934. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  935. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  936. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  937. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  938. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  939. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  940. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  941. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  942. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  943. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  944. self.ui.menuhelp_about.triggered.connect(self.on_about)
  945. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  946. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  947. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  948. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  949. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  950. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  951. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  952. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  953. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  954. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  955. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  956. # Toolbar
  957. #self.ui.file_new_btn.triggered.connect(self.on_file_new)
  958. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  959. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  960. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  961. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  962. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  963. self.ui.replot_btn.triggered.connect(self.plot_all)
  964. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  965. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  966. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  967. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  968. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  969. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  970. self.ui.update_obj_btn.triggered.connect(self.editor2object)
  971. self.ui.delete_btn.triggered.connect(self.on_delete)
  972. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  973. # Context Menu
  974. self.ui.popmenu_disable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  975. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  976. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  977. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  978. self.ui.gridmenu_1.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.05"))
  979. self.ui.gridmenu_2.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.1"))
  980. self.ui.gridmenu_3.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.2"))
  981. self.ui.gridmenu_4.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.5"))
  982. self.ui.gridmenu_5.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("1.0"))
  983. self.ui.draw_line.triggered.connect(self.geo_editor.draw_tool_path)
  984. self.ui.draw_rect.triggered.connect(self.geo_editor.draw_tool_rectangle)
  985. self.ui.draw_cut.triggered.connect(self.geo_editor.cutpath)
  986. self.ui.draw_move.triggered.connect(self.geo_editor.on_move)
  987. self.ui.drill.triggered.connect(self.exc_editor.exc_add_drill)
  988. self.ui.drill_array.triggered.connect(self.exc_editor.exc_add_drill_array)
  989. self.ui.drill_copy.triggered.connect(self.exc_editor.exc_copy_drills)
  990. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  991. self.ui.clearplot.triggered.connect(self.clear_plots)
  992. self.ui.replot.triggered.connect(self.plot_all)
  993. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  994. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  995. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  996. self.ui.popmenu_save.triggered.connect(self.editor2object)
  997. self.ui.popmenu_move.triggered.connect(self.obj_move)
  998. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  999. # Preferences Plot Area TAB
  1000. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1001. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1002. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1003. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1004. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1005. ###############################
  1006. ### GUI PREFERENCES SIGNALS ###
  1007. ###############################
  1008. self.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1009. self.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(self.on_language_apply)
  1010. ###############################
  1011. ### GUI PREFERENCES SIGNALS ###
  1012. ###############################
  1013. # Setting plot colors signals
  1014. self.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(self.on_pf_color_entry)
  1015. self.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(self.on_pf_color_button)
  1016. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(self.on_pf_color_spinner)
  1017. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(self.on_pf_color_slider)
  1018. self.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(self.on_pl_color_entry)
  1019. self.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(self.on_pl_color_button)
  1020. # Setting selection (left - right) colors signals
  1021. self.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(self.on_sf_color_entry)
  1022. self.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(self.on_sf_color_button)
  1023. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(self.on_sf_color_spinner)
  1024. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(self.on_sf_color_slider)
  1025. self.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(self.on_sl_color_entry)
  1026. self.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(self.on_sl_color_button)
  1027. # Setting selection (right - left) colors signals
  1028. self.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(self.on_alt_sf_color_entry)
  1029. self.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(self.on_alt_sf_color_button)
  1030. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1031. self.on_alt_sf_color_spinner)
  1032. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1033. self.on_alt_sf_color_slider)
  1034. self.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(self.on_alt_sl_color_entry)
  1035. self.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(self.on_alt_sl_color_button)
  1036. # Setting Editor Draw colors signals
  1037. self.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(self.on_draw_color_entry)
  1038. self.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(self.on_draw_color_button)
  1039. self.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(self.on_sel_draw_color_entry)
  1040. self.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(self.on_sel_draw_color_button)
  1041. self.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1042. self.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1043. self.general_defaults_form.general_gui_group.layout_combo.activated.connect(self.on_layout)
  1044. # Modify G-CODE Plot Area TAB
  1045. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1046. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1047. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1048. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1049. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1050. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1051. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1052. # Object list
  1053. self.collection.view.activated.connect(self.on_row_activated)
  1054. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1055. self.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1056. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1057. self.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1058. self.on_excellon_defaults_button)
  1059. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1060. self.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1061. self.on_excellon_options_button)
  1062. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1063. self.tool_tab_locked = False
  1064. ####################
  1065. ### Other setups ###
  1066. ####################
  1067. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1068. self.setup_obj_classes()
  1069. self.setup_recent_items()
  1070. self.setup_component_editor()
  1071. #############
  1072. ### Shell ###
  1073. #############
  1074. ###
  1075. # Auto-complete KEYWORDS
  1076. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1077. 'aligndrill', 'clear',
  1078. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1079. 'export_gcode',
  1080. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1081. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1082. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1083. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1084. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1085. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1086. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1087. ]
  1088. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1089. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  1090. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  1091. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  1092. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  1093. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  1094. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  1095. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  1096. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1097. ]
  1098. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords
  1099. self.shell = FCShell(self, version=self.version)
  1100. self.shell._edit.set_model_data(self.myKeywords)
  1101. self.shell.setWindowIcon(self.ui.app_icon)
  1102. self.shell.setWindowTitle("FlatCAM Shell")
  1103. self.shell.resize(*self.defaults["global_shell_shape"])
  1104. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1105. self.shell.append_output("(Type help to get started)\n\n")
  1106. self.init_tcl()
  1107. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1108. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1109. self.ui.shell_dock.setWidget(self.shell)
  1110. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1111. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1112. QtWidgets.QDockWidget.DockWidgetFloatable |
  1113. QtWidgets.QDockWidget.DockWidgetClosable)
  1114. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1115. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1116. if self.defaults["global_shell_at_startup"]:
  1117. self.ui.shell_dock.show()
  1118. else:
  1119. self.ui.shell_dock.hide()
  1120. #########################
  1121. ### Tools and Plugins ###
  1122. #########################
  1123. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1124. self.install_tools()
  1125. ### System Font Parsing ###
  1126. # self.f_parse = ParseFont(self)
  1127. # self.parse_system_fonts()
  1128. # test if the program was started with a script as parameter
  1129. if self.cmd_line_shellfile:
  1130. try:
  1131. with open(self.cmd_line_shellfile, "r") as myfile:
  1132. cmd_line_shellfile_text = myfile.read()
  1133. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1134. except Exception as ext:
  1135. print("ERROR: ", ext)
  1136. sys.exit(2)
  1137. ###########################
  1138. #### Check for updates ####
  1139. ###########################
  1140. # Separate thread (Not worker)
  1141. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1142. if (self.beta is False or self.beta is None) and \
  1143. self.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1144. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1145. self.thr2 = QtCore.QThread()
  1146. self.worker_task.emit({'fcn': self.version_check,
  1147. 'params': []})
  1148. self.thr2.start()
  1149. ####################################
  1150. #### Variables for global usage ####
  1151. ####################################
  1152. # coordinates for relative position display
  1153. self.rel_point1 = (0, 0)
  1154. self.rel_point2 = (0, 0)
  1155. # variable to store coordinates
  1156. self.pos = (0, 0)
  1157. self.pos_jump = (0, 0)
  1158. # variable to store if there was motion before right mouse button click (panning)
  1159. self.panning_action = False
  1160. # variable to store if a command is active (then the var is not None) and which one it is
  1161. self.command_active = None
  1162. # variable to store the status of moving selection action
  1163. # None value means that it's not an selection action
  1164. # True value = a selection from left to right
  1165. # False value = a selection from right to left
  1166. self.selection_type = None
  1167. # List to store the objects that are currently loaded in FlatCAM
  1168. # This list is updated on each object creation or object delete
  1169. self.all_objects_list = []
  1170. # List to store the objects that are selected
  1171. self.sel_objects_list = []
  1172. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1173. self.key_modifiers = None
  1174. # Variable to hold the status of the axis
  1175. self.toggle_axis = True
  1176. # Variable to store the status of the fullscreen event
  1177. self.toggle_fscreen = False
  1178. self.cursor = None
  1179. # Variable to store the GCODE that was edited
  1180. self.gcode_edited = ""
  1181. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3', 'gko',
  1182. 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15', 'dim', 'mil',
  1183. 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo', 'art', 'gbd']
  1184. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1185. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1186. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1187. 'mpf']
  1188. self.svg_list = ['svg']
  1189. self.dxf_list = ['dxf']
  1190. self.prj_list = ['flatprj']
  1191. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1192. # flag for polygons not cleared
  1193. self.poly_not_cleared = False
  1194. ### Save defaults to factory_defaults.FlatConfig file ###
  1195. ### It's done only once after install #############
  1196. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1197. fac_def_from_file = factory_file.read()
  1198. factory_defaults = json.loads(fac_def_from_file)
  1199. # if the file contain an empty dictionary then save the factory defaults into the file
  1200. if not factory_defaults:
  1201. self.save_factory_defaults(silent=False)
  1202. factory_file.close()
  1203. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1204. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1205. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1206. # Post-GUI initialization: Experimental attempt
  1207. # to perform unit tests on the GUI.
  1208. # if post_gui is not None:
  1209. # post_gui(self)
  1210. App.log.debug("END of constructor. Releasing control.")
  1211. # accept a project file as command line parameter
  1212. # the path/file_name must be enclosed in quotes if it contain spaces
  1213. for argument in App.args:
  1214. if '.FlatPrj' in argument:
  1215. try:
  1216. project_name = str(argument)
  1217. if project_name == "":
  1218. self.inform.emit("Open cancelled.")
  1219. else:
  1220. # self.open_project(project_name)
  1221. run_from_arg = True
  1222. self.worker_task.emit({'fcn': self.open_project,
  1223. 'params': [project_name, run_from_arg]})
  1224. except Exception as e:
  1225. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1226. def defaults_read_form(self):
  1227. for option in self.defaults_form_fields:
  1228. try:
  1229. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1230. except:
  1231. pass
  1232. def defaults_write_form(self):
  1233. for option in self.defaults:
  1234. self.defaults_write_form_field(option)
  1235. # try:
  1236. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1237. # except KeyError:
  1238. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1239. # # TODO: Rethink this?
  1240. # pass
  1241. def defaults_write_form_field(self, field):
  1242. try:
  1243. self.defaults_form_fields[field].set_value(self.defaults[field])
  1244. except KeyError:
  1245. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1246. # TODO: Rethink this?
  1247. pass
  1248. def clear_pool(self):
  1249. self.pool.close()
  1250. self.pool = Pool()
  1251. self.pool_recreated.emit(self.pool)
  1252. gc.collect()
  1253. # the order that the tools are installed is important as they can depend on each other install position
  1254. def install_tools(self):
  1255. self.dblsidedtool = DblSidedTool(self)
  1256. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1257. self.measurement_tool = Measurement(self)
  1258. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1259. self.panelize_tool = Panelize(self)
  1260. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1261. self.film_tool = Film(self)
  1262. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'), separator=True)
  1263. self.move_tool = ToolMove(self)
  1264. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1265. before=self.ui.menueditorigin)
  1266. self.cutout_tool = ToolCutOut(self)
  1267. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16.png'), pos=self.ui.menutool,
  1268. before=self.measurement_tool.menuAction)
  1269. self.ncclear_tool = NonCopperClear(self)
  1270. self.ncclear_tool.install(icon=QtGui.QIcon('share/flatcam_icon16.png'), pos=self.ui.menutool,
  1271. before=self.measurement_tool.menuAction, separator=True)
  1272. self.paint_tool = ToolPaint(self)
  1273. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1274. before=self.measurement_tool.menuAction, separator=True)
  1275. self.calculator_tool = ToolCalculator(self)
  1276. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1277. self.transform_tool = ToolTransform(self)
  1278. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1279. self.properties_tool = Properties(self)
  1280. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1281. self.image_tool = ToolImage(self)
  1282. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1283. separator=True)
  1284. self.log.debug("Tools are installed.")
  1285. def remove_tools(self):
  1286. for act in self.ui.menutool.actions():
  1287. self.ui.menutool.removeAction(act)
  1288. def init_tools(self):
  1289. log.debug("init_tools()")
  1290. # delete the data currently in the Tools Tab and the Tab itself
  1291. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1292. if widget is not None:
  1293. widget.deleteLater()
  1294. self.ui.notebook.removeTab(2)
  1295. # rebuild the Tools Tab
  1296. self.ui.tool_tab = QtWidgets.QWidget()
  1297. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1298. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1299. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1300. self.ui.tool_scroll_area = VerticalScrollArea()
  1301. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1302. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1303. # first remove all of them
  1304. self.remove_tools()
  1305. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1306. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  1307. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1308. # third install all of them
  1309. self.install_tools()
  1310. self.log.debug("Tools are initialized.")
  1311. # def parse_system_fonts(self):
  1312. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1313. # 'params': []})
  1314. def object2editor(self):
  1315. """
  1316. Send the current Geometry or Excellon object (if any) into the editor.
  1317. :return: None
  1318. """
  1319. self.report_usage("object2editor()")
  1320. # adjust the visibility of some of the canvas context menu
  1321. self.ui.popmenu_edit.setVisible(False)
  1322. self.ui.popmenu_save.setVisible(True)
  1323. edited_object = self.collection.get_active()
  1324. if isinstance(edited_object, FlatCAMGeometry):
  1325. # for now, if the Geometry is MultiGeo do not allow the editing
  1326. if edited_object.multigeo is True:
  1327. self.inform.emit("[WARNING_NOTCL]Editing a MultiGeo Geometry is not possible for the moment.")
  1328. return
  1329. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1330. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1331. self.geo_editor.edit_fcgeometry(edited_object)
  1332. # set call source to the Editor we go into
  1333. self.call_source = 'geo_editor'
  1334. elif isinstance(edited_object, FlatCAMExcellon):
  1335. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1336. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1337. self.exc_editor.edit_fcexcellon(edited_object)
  1338. # set call source to the Editor we go into
  1339. self.call_source = 'exc_editor'
  1340. else:
  1341. self.inform.emit("[WARNING_NOTCL]Select a Geometry or Excellon Object to edit.")
  1342. return
  1343. # make sure that we can't select another object while in Editor Mode:
  1344. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1345. # delete any selection shape that might be active as they are not relevant in Editor
  1346. self.delete_selection_shape()
  1347. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1348. self.ui.plot_tab_area.protectTab(0)
  1349. self.inform.emit("[WARNING_NOTCL]Editor is activated ...")
  1350. def editor2object(self):
  1351. """
  1352. Transfers the Geometry or Excellon from the editor to the current object.
  1353. :return: None
  1354. """
  1355. self.report_usage("editor2object()")
  1356. # adjust the visibility of some of the canvas context menu
  1357. self.ui.popmenu_edit.setVisible(True)
  1358. self.ui.popmenu_save.setVisible(False)
  1359. edited_obj = self.collection.get_active()
  1360. obj_type = ""
  1361. if isinstance(edited_obj, FlatCAMGeometry):
  1362. obj_type = "Geometry"
  1363. self.geo_editor.update_fcgeometry(edited_obj)
  1364. self.geo_editor.update_options(edited_obj)
  1365. self.geo_editor.deactivate()
  1366. # update the geo object options so it is including the bounding box values
  1367. try:
  1368. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1369. edited_obj.options['xmin'] = xmin
  1370. edited_obj.options['ymin'] = ymin
  1371. edited_obj.options['xmax'] = xmax
  1372. edited_obj.options['ymax'] = ymax
  1373. except AttributeError:
  1374. self.inform.emit("[WARNING] Object empty after edit.")
  1375. elif isinstance(edited_obj, FlatCAMExcellon):
  1376. obj_type = "Excellon"
  1377. self.exc_editor.update_fcexcellon(edited_obj)
  1378. self.exc_editor.update_options(edited_obj)
  1379. self.exc_editor.deactivate()
  1380. else:
  1381. self.inform.emit("[WARNING_NOTCL]Select a Geometry or Excellon Object to update.")
  1382. return
  1383. # restore the call_source to app
  1384. self.call_source = 'app'
  1385. edited_obj.plot()
  1386. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1387. self.ui.plot_tab_area.protectTab(0)
  1388. self.inform.emit("[selected] %s is updated, returning to App..." % obj_type)
  1389. # reset the Object UI to original settings
  1390. # edited_obj.set_ui(edited_obj.ui_type())
  1391. # edited_obj.build_ui()
  1392. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1393. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1394. def get_last_folder(self):
  1395. return self.defaults["global_last_folder"]
  1396. def get_last_save_folder(self):
  1397. loc = self.defaults["global_last_save_folder"]
  1398. if loc is None:
  1399. loc = self.defaults["global_last_folder"]
  1400. if loc is None:
  1401. loc = os.path.dirname(__file__)
  1402. return loc
  1403. def report_usage(self, resource):
  1404. """
  1405. Increments usage counter for the given resource
  1406. in self.defaults['global_stats'].
  1407. :param resource: Name of the resource.
  1408. :return: None
  1409. """
  1410. if resource in self.defaults['global_stats']:
  1411. self.defaults['global_stats'][resource] += 1
  1412. else:
  1413. self.defaults['global_stats'][resource] = 1
  1414. def init_tcl(self):
  1415. if hasattr(self,'tcl'):
  1416. # self.tcl = None
  1417. # TODO we need to clean non default variables and procedures here
  1418. # new object cannot be used here as it will not remember values created for next passes,
  1419. # because tcl was execudted in old instance of TCL
  1420. pass
  1421. else:
  1422. self.tcl = tk.Tcl()
  1423. self.setup_shell()
  1424. self.log.debug("TCL Shell has been initialized.")
  1425. # TODO: This shouldn't be here.
  1426. class TclErrorException(Exception):
  1427. """
  1428. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1429. """
  1430. pass
  1431. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  1432. """
  1433. Shows a message on the FlatCAM Shell
  1434. :param msg: Message to display.
  1435. :param show: Opens the shell.
  1436. :param error: Shows the message as an error.
  1437. :return: None
  1438. """
  1439. if show:
  1440. self.ui.shell_dock.show()
  1441. try:
  1442. if error:
  1443. self.shell.append_error(msg + "\n")
  1444. elif warning:
  1445. self.shell.append_warning(msg + "\n")
  1446. elif success:
  1447. self.shell.append_success(msg + "\n")
  1448. elif selected:
  1449. self.shell.append_selected(msg + "\n")
  1450. else:
  1451. self.shell.append_output(msg + "\n")
  1452. except AttributeError:
  1453. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1454. def raise_tcl_unknown_error(self, unknownException):
  1455. """
  1456. Raise exception if is different type than TclErrorException
  1457. this is here mainly to show unknown errors inside TCL shell console.
  1458. :param unknownException:
  1459. :return:
  1460. """
  1461. if not isinstance(unknownException, self.TclErrorException):
  1462. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  1463. else:
  1464. raise unknownException
  1465. def display_tcl_error(self, error, error_info=None):
  1466. """
  1467. escape bracket [ with \ otherwise there is error
  1468. "ERROR: missing close-bracket" instead of real error
  1469. :param error: it may be text or exception
  1470. :return: None
  1471. """
  1472. if isinstance(error, Exception):
  1473. exc_type, exc_value, exc_traceback = error_info
  1474. if not isinstance(error, self.TclErrorException):
  1475. show_trace = 1
  1476. else:
  1477. show_trace = int(self.defaults['global_verbose_error_level'])
  1478. if show_trace > 0:
  1479. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  1480. trc_formated = []
  1481. for a in reversed(trc):
  1482. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  1483. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  1484. exc_type,
  1485. "\n".join(trc_formated))
  1486. else:
  1487. text = "%s" % error
  1488. else:
  1489. text = error
  1490. text = text.replace('[', '\\[').replace('"', '\\"')
  1491. self.tcl.eval('return -code error "%s"' % text)
  1492. def raise_tcl_error(self, text):
  1493. """
  1494. this method pass exception from python into TCL as error, so we get stacktrace and reason
  1495. :param text: text of error
  1496. :return: raise exception
  1497. """
  1498. self.display_tcl_error(text)
  1499. raise self.TclErrorException(text)
  1500. def exec_command(self, text):
  1501. """
  1502. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1503. Also handles execution in separated threads
  1504. :param text:
  1505. :return: output if there was any
  1506. """
  1507. self.report_usage('exec_command')
  1508. result = self.exec_command_test(text, False)
  1509. #MS: added this method call so the geometry is updated once the TCL
  1510. #command is executed
  1511. self.plot_all()
  1512. return result
  1513. def exec_command_test(self, text, reraise=True):
  1514. """
  1515. Same as exec_command(...) with additional control over exceptions.
  1516. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1517. :param text: Input command
  1518. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  1519. :return: Output from the command
  1520. """
  1521. text = str(text)
  1522. try:
  1523. self.shell.open_proccessing() # Disables input box.
  1524. result = self.tcl.eval(str(text))
  1525. if result != 'None':
  1526. self.shell.append_output(result + '\n')
  1527. except tk.TclError as e:
  1528. # This will display more precise answer if something in TCL shell fails
  1529. result = self.tcl.eval("set errorInfo")
  1530. self.log.error("Exec command Exception: %s" % (result + '\n'))
  1531. self.shell.append_error('ERROR: ' + result + '\n')
  1532. # Show error in console and just return or in test raise exception
  1533. if reraise:
  1534. raise e
  1535. finally:
  1536. self.shell.close_proccessing()
  1537. pass
  1538. return result
  1539. # """
  1540. # Code below is unsused. Saved for later.
  1541. # """
  1542. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  1543. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  1544. # self.log.debug(parts)
  1545. # try:
  1546. # if parts[0] not in commands:
  1547. # self.shell.append_error("Unknown command\n")
  1548. # return
  1549. #
  1550. # #import inspect
  1551. # #inspect.getargspec(someMethod)
  1552. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  1553. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  1554. # self.shell.append_error(
  1555. # "Command %s takes %d arguments. %d given.\n" %
  1556. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  1557. # )
  1558. # return
  1559. #
  1560. # cmdfcn = commands[parts[0]]["fcn"]
  1561. # cmdconv = commands[parts[0]]["converters"]
  1562. # if len(parts) - 1 > 0:
  1563. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  1564. # else:
  1565. # retval = cmdfcn()
  1566. # retfcn = commands[parts[0]]["retfcn"]
  1567. # if retval and retfcn(retval):
  1568. # self.shell.append_output(retfcn(retval) + "\n")
  1569. #
  1570. # except Exception as e:
  1571. # #self.shell.append_error(''.join(traceback.format_exc()))
  1572. # #self.shell.append_error("?\n")
  1573. # self.shell.append_error(str(e) + "\n")
  1574. def info(self, msg):
  1575. """
  1576. Informs the user. Normally on the status bar, optionally
  1577. also on the shell.
  1578. :param msg: Text to write.
  1579. :return: None
  1580. """
  1581. # Type of message in brackets at the begining of the message.
  1582. match = re.search("\[([^\]]+)\](.*)", msg)
  1583. if match:
  1584. level = match.group(1)
  1585. msg_ = match.group(2)
  1586. self.ui.fcinfo.set_status(str(msg_), level=level)
  1587. if level.lower() == "error":
  1588. self.shell_message(msg, error=True, show=True)
  1589. elif level.lower() == "warning":
  1590. self.shell_message(msg, warning=True, show=True)
  1591. elif level.lower() == "error_notcl":
  1592. self.shell_message(msg, error=True, show=False)
  1593. elif level.lower() == "warning_notcl":
  1594. self.shell_message(msg, warning=True, show=False)
  1595. elif level.lower() == "success":
  1596. self.shell_message(msg, success=True, show=False)
  1597. elif level.lower() == "selected":
  1598. self.shell_message(msg, selected=True, show=False)
  1599. else:
  1600. self.shell_message(msg, show=False)
  1601. else:
  1602. self.ui.fcinfo.set_status(str(msg), level="info")
  1603. # make sure that if the message is to clear the infobar with a space
  1604. # is not printed over and over on the shell
  1605. if msg != '':
  1606. self.shell_message(msg)
  1607. def restore_toolbar_view(self):
  1608. tb = self.defaults["global_toolbar_view"]
  1609. if tb & 1:
  1610. self.ui.toolbarfile.setVisible(True)
  1611. else:
  1612. self.ui.toolbarfile.setVisible(False)
  1613. if tb & 2:
  1614. self.ui.toolbargeo.setVisible(True)
  1615. else:
  1616. self.ui.toolbargeo.setVisible(False)
  1617. if tb & 4:
  1618. self.ui.toolbarview.setVisible(True)
  1619. else:
  1620. self.ui.toolbarview.setVisible(False)
  1621. if tb & 8:
  1622. self.ui.toolbartools.setVisible(True)
  1623. else:
  1624. self.ui.toolbartools.setVisible(False)
  1625. if tb & 16:
  1626. self.ui.exc_edit_toolbar.setVisible(True)
  1627. else:
  1628. self.ui.exc_edit_toolbar.setVisible(False)
  1629. if tb & 32:
  1630. self.ui.geo_edit_toolbar.setVisible(True)
  1631. else:
  1632. self.ui.geo_edit_toolbar.setVisible(False)
  1633. if tb & 64:
  1634. self.ui.snap_toolbar.setVisible(True)
  1635. else:
  1636. self.ui.snap_toolbar.setVisible(False)
  1637. def load_defaults(self, filename):
  1638. """
  1639. Loads the aplication's default settings from current_defaults.FlatConfig into
  1640. ``self.defaults``.
  1641. :return: None
  1642. """
  1643. try:
  1644. f = open(self.data_path + "/" + filename + ".FlatConfig")
  1645. options = f.read()
  1646. f.close()
  1647. except IOError:
  1648. self.log.error("Could not load defaults file.")
  1649. self.inform.emit("[ERROR] Could not load defaults file.")
  1650. # in case the defaults file can't be loaded, show all toolbars
  1651. self.defaults["global_toolbar_view"] = 127
  1652. return
  1653. try:
  1654. defaults = json.loads(options)
  1655. except:
  1656. # in case the defaults file can't be loaded, show all toolbars
  1657. self.defaults["global_toolbar_view"] = 127
  1658. e = sys.exc_info()[0]
  1659. App.log.error(str(e))
  1660. self.inform.emit("[ERROR] Failed to parse defaults file.")
  1661. return
  1662. self.defaults.update(defaults)
  1663. log.debug("FlatCAM defaults loaded from: %s" % filename)
  1664. # restore the toolbar view
  1665. self.restore_toolbar_view()
  1666. def on_import_preferences(self):
  1667. """
  1668. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  1669. ``self.defaults``.
  1670. :return: None
  1671. """
  1672. self.report_usage("on_import_preferences")
  1673. App.log.debug("on_import_preferences()")
  1674. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1675. try:
  1676. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences",
  1677. directory=self.data_path, filter=filter)
  1678. except TypeError:
  1679. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences", filter=filter)
  1680. filename = str(filename)
  1681. if filename == "":
  1682. self.inform.emit("[WARNING_NOTCL]FlatCAM preferences import cancelled.")
  1683. else:
  1684. try:
  1685. f = open(filename)
  1686. options = f.read()
  1687. f.close()
  1688. except IOError:
  1689. self.log.error("Could not load defaults file.")
  1690. self.inform.emit("[ERROR_NOTCL] Could not load defaults file.")
  1691. return
  1692. try:
  1693. defaults_from_file = json.loads(options)
  1694. except:
  1695. e = sys.exc_info()[0]
  1696. App.log.error(str(e))
  1697. self.inform.emit("[ERROR_NOTCL] Failed to parse defaults file.")
  1698. return
  1699. self.defaults.update(defaults_from_file)
  1700. self.inform.emit("[success]Imported Defaults from %s" %filename)
  1701. def on_export_preferences(self):
  1702. self.report_usage("on_export_preferences")
  1703. App.log.debug("on_export_preferences()")
  1704. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1705. try:
  1706. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  1707. caption="Export FlatCAM Preferences",
  1708. directory=self.data_path + '/preferences_' + self.date.replace('-', ''), filter=filter
  1709. )
  1710. except TypeError:
  1711. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export FlatCAM Preferences", filter=filter)
  1712. filename = str(filename)
  1713. defaults_from_file = {}
  1714. if filename == "":
  1715. self.inform.emit("[WARNING_NOTCL]FlatCAM preferences export cancelled.")
  1716. return
  1717. else:
  1718. try:
  1719. f = open(filename, 'w')
  1720. defaults_file_content = f.read()
  1721. f.close()
  1722. except IOError:
  1723. App.log.debug('Creating a new preferences file ...')
  1724. f = open(filename, 'w')
  1725. json.dump({}, f)
  1726. f.close()
  1727. except:
  1728. e = sys.exc_info()[0]
  1729. App.log.error("Could not load defaults file.")
  1730. App.log.error(str(e))
  1731. self.inform.emit("[ERROR_NOTCL]Could not load defaults file.")
  1732. return
  1733. try:
  1734. defaults_from_file = json.loads(defaults_file_content)
  1735. except:
  1736. App.log.warning("Trying to read an empty Preferences file. Continue.")
  1737. # Update options
  1738. self.defaults_read_form()
  1739. defaults_from_file.update(self.defaults)
  1740. self.propagate_defaults(silent=True)
  1741. # Save update options
  1742. try:
  1743. f = open(filename, "w")
  1744. json.dump(defaults_from_file, f)
  1745. f.close()
  1746. except:
  1747. self.inform.emit("[ERROR_NOTCL] Failed to write defaults to file.")
  1748. return
  1749. self.file_saved.emit("preferences", filename)
  1750. self.inform.emit("[success]Exported Defaults to %s" % filename)
  1751. def on_preferences_open_folder(self):
  1752. self.report_usage("on_preferences_open_folder()")
  1753. if sys.platform == 'win32':
  1754. subprocess.Popen('explorer %s' % self.data_path)
  1755. elif sys.platform == 'darwin':
  1756. os.system('open "%s"' % self.data_path)
  1757. else:
  1758. subprocess.Popen(['xdg-open', self.data_path])
  1759. self.inform.emit("[success]FlatCAM Preferences Folder opened.")
  1760. def save_geometry(self, x, y, width, height, notebook_width):
  1761. self.defaults["global_def_win_x"] = x
  1762. self.defaults["global_def_win_y"] = y
  1763. self.defaults["global_def_win_w"] = width
  1764. self.defaults["global_def_win_h"] = height
  1765. self.defaults["def_notebook_width"] = notebook_width
  1766. self.save_defaults()
  1767. def message_dialog(self, title, message, kind="info"):
  1768. icon = {"info": QtWidgets.QMessageBox.Information,
  1769. "warning": QtWidgets.QMessageBox.Warning,
  1770. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  1771. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  1772. dlg.setText(message)
  1773. dlg.exec_()
  1774. def register_recent(self, kind, filename):
  1775. self.log.debug("register_recent()")
  1776. self.log.debug(" %s" % kind)
  1777. self.log.debug(" %s" % filename)
  1778. record = {'kind': str(kind), 'filename': str(filename)}
  1779. if record in self.recent:
  1780. return
  1781. self.recent.insert(0, record)
  1782. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  1783. self.recent.pop()
  1784. try:
  1785. f = open(self.data_path + '/recent.json', 'w')
  1786. except IOError:
  1787. App.log.error("Failed to open recent items file for writing.")
  1788. self.inform.emit('[ERROR_NOTCL]Failed to open recent files file for writing.')
  1789. return
  1790. #try:
  1791. json.dump(self.recent, f)
  1792. # except:
  1793. # App.log.error("Failed to write to recent items file.")
  1794. # self.inform.emit('ERROR: Failed to write to recent items file.')
  1795. # f.close()
  1796. f.close()
  1797. # Re-buid the recent items menu
  1798. self.setup_recent_items()
  1799. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  1800. """
  1801. Creates a new specalized FlatCAMObj and attaches it to the application,
  1802. this is, updates the GUI accordingly, any other records and plots it.
  1803. This method is thread-safe.
  1804. Notes:
  1805. * If the name is in use, the self.collection will modify it
  1806. when appending it to the collection. There is no need to handle
  1807. name conflicts here.
  1808. :param kind: The kind of object to create. One of 'gerber',
  1809. 'excellon', 'cncjob' and 'geometry'.
  1810. :type kind: str
  1811. :param name: Name for the object.
  1812. :type name: str
  1813. :param initialize: Function to run after creation of the object
  1814. but before it is attached to the application. The function is
  1815. called with 2 parameters: the new object and the App instance.
  1816. :type initialize: function
  1817. :return: None
  1818. :rtype: None
  1819. """
  1820. App.log.debug("new_object()")
  1821. self.plot = plot
  1822. self.autoselected = autoselected
  1823. t0 = time.time() # Debug
  1824. ## Create object
  1825. classdict = {
  1826. "gerber": FlatCAMGerber,
  1827. "excellon": FlatCAMExcellon,
  1828. "cncjob": FlatCAMCNCjob,
  1829. "geometry": FlatCAMGeometry
  1830. }
  1831. App.log.debug("Calling object constructor...")
  1832. obj = classdict[kind](name)
  1833. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  1834. # Set options from "Project options" form
  1835. self.options_read_form()
  1836. # IMPORTANT
  1837. # The key names in defaults and options dictionary's are not random:
  1838. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  1839. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  1840. # the options from project options form into the self.options. After that, below, depending on the type of
  1841. # object that is created, it will strip the name of the object and the underline (if the original key was
  1842. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  1843. # "toolchange"
  1844. for option in self.options:
  1845. if option.find(kind + "_") == 0:
  1846. oname = option[len(kind) + 1:]
  1847. obj.options[oname] = self.options[option]
  1848. # if kind == 'geometry':
  1849. # obj.tools = {}
  1850. # elif kind == 'cncjob':
  1851. # obj.cnc_tools = {}
  1852. # Initialize as per user request
  1853. # User must take care to implement initialize
  1854. # in a thread-safe way as is is likely that we
  1855. # have been invoked in a separate thread.
  1856. t1 = time.time()
  1857. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  1858. try:
  1859. return_value = initialize(obj, self)
  1860. except Exception as e:
  1861. msg = "[ERROR_NOTCL] An internal error has ocurred. See shell.\n"
  1862. msg += "Object (%s) failed because: %s \n\n" % (kind, str(e))
  1863. msg += traceback.format_exc()
  1864. self.inform.emit(msg)
  1865. # if str(e) == "Empty Geometry":
  1866. # self.inform.emit("[ERROR_NOTCL] )
  1867. # else:
  1868. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  1869. return "fail"
  1870. t2 = time.time()
  1871. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  1872. if return_value == 'fail':
  1873. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  1874. return "fail"
  1875. # Check units and convert if necessary
  1876. # This condition CAN be true because initialize() can change obj.units
  1877. if self.options["units"].upper() != obj.units.upper():
  1878. self.inform.emit("Converting units to " + self.options["units"] + ".")
  1879. obj.convert_units(self.options["units"])
  1880. t3 = time.time()
  1881. self.log.debug("%f seconds converting units." % (t3 - t2))
  1882. # Create the bounding box for the object and then add the results to the obj.options
  1883. try:
  1884. xmin, ymin, xmax, ymax = obj.bounds()
  1885. obj.options['xmin'] = xmin
  1886. obj.options['ymin'] = ymin
  1887. obj.options['xmax'] = xmax
  1888. obj.options['ymax'] = ymax
  1889. except:
  1890. log.warning("The object has no bounds properties.")
  1891. # don't plot objects with no bounds, there is nothing to plot
  1892. self.plot = False
  1893. pass
  1894. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  1895. # Move the object to the main thread and let the app know that it is available.
  1896. obj.moveToThread(QtWidgets.QApplication.instance().thread())
  1897. self.object_created.emit(obj, self.plot, self.autoselected)
  1898. return obj
  1899. def new_excellon_object(self):
  1900. self.report_usage("new_excellon_object()")
  1901. self.new_object('excellon', 'new_e', lambda x, y: None, plot=False)
  1902. def new_geometry_object(self):
  1903. self.report_usage("new_geometry_object()")
  1904. def initialize(obj, self):
  1905. obj.multitool = False
  1906. self.new_object('geometry', 'new_g', initialize, plot=False)
  1907. def on_object_created(self, obj, plot, autoselect):
  1908. """
  1909. Event callback for object creation.
  1910. :param obj: The newly created FlatCAM object.
  1911. :return: None
  1912. """
  1913. t0 = time.time() # DEBUG
  1914. self.log.debug("on_object_created()")
  1915. # The Collection might change the name if there is a collision
  1916. self.collection.append(obj)
  1917. # after adding the object to the collection always update the list of objects that are in the collection
  1918. self.all_objects_list = self.collection.get_list()
  1919. # self.inform.emit('[selected] %s created & selected: %s' %
  1920. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  1921. if obj.kind == 'gerber':
  1922. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1923. (obj.kind.capitalize(), 'green', str(obj.options['name'])))
  1924. elif obj.kind == 'excellon':
  1925. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1926. (obj.kind.capitalize(), 'brown', str(obj.options['name'])))
  1927. elif obj.kind == 'cncjob':
  1928. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1929. (obj.kind.capitalize(), 'blue', str(obj.options['name'])))
  1930. elif obj.kind == 'geometry':
  1931. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1932. (obj.kind.capitalize(), 'red', str(obj.options['name'])))
  1933. # self.new_object_available.emit(obj)
  1934. # update the SHELL auto-completer model with the name of the new object
  1935. self.myKeywords.append(obj.options['name'])
  1936. self.shell._edit.set_model_data(self.myKeywords)
  1937. if autoselect:
  1938. # select the just opened object but deselect the previous ones
  1939. self.collection.set_all_inactive()
  1940. self.collection.set_active(obj.options["name"])
  1941. # here it is done the object plotting
  1942. def worker_task(obj):
  1943. with self.proc_container.new("Plotting"):
  1944. if isinstance(obj, FlatCAMCNCjob):
  1945. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  1946. else:
  1947. obj.plot()
  1948. t1 = time.time() # DEBUG
  1949. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  1950. self.object_plotted.emit(obj)
  1951. # Send to worker
  1952. # self.worker.add_task(worker_task, [self])
  1953. if plot is True:
  1954. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  1955. def on_object_changed(self, obj):
  1956. # update the bounding box data from obj.options
  1957. xmin, ymin, xmax, ymax = obj.bounds()
  1958. obj.options['xmin'] = xmin
  1959. obj.options['ymin'] = ymin
  1960. obj.options['xmax'] = xmax
  1961. obj.options['ymax'] = ymax
  1962. log.debug("Object changed, updating the bounding box data on self.options")
  1963. # delete the old selection shape
  1964. self.delete_selection_shape()
  1965. def on_object_plotted(self, obj):
  1966. self.on_zoom_fit(None)
  1967. def options_read_form(self):
  1968. for option in self.options_form_fields:
  1969. self.options[option] = self.options_form_fields[option].get_value()
  1970. def options_write_form(self):
  1971. for option in self.options:
  1972. self.options_write_form_field(option)
  1973. def options_write_form_field(self, field):
  1974. try:
  1975. self.options_form_fields[field].set_value(self.options[field])
  1976. except KeyError:
  1977. # Changed from error to debug. This allows to have data stored
  1978. # which is not user-editable.
  1979. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  1980. pass
  1981. def on_about(self):
  1982. """
  1983. Displays the "about" dialog.
  1984. :return: None
  1985. """
  1986. self.report_usage("on_about")
  1987. version = self.version
  1988. version_date = self.version_date
  1989. beta = self.beta
  1990. class AboutDialog(QtWidgets.QDialog):
  1991. def __init__(self, parent=None):
  1992. QtWidgets.QDialog.__init__(self, parent)
  1993. # Icon and title
  1994. self.setWindowIcon(parent.app_icon)
  1995. self.setWindowTitle("FlatCAM")
  1996. layout1 = QtWidgets.QVBoxLayout()
  1997. self.setLayout(layout1)
  1998. layout2 = QtWidgets.QHBoxLayout()
  1999. layout1.addLayout(layout2)
  2000. logo = QtWidgets.QLabel()
  2001. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2002. layout2.addWidget(logo, stretch=0)
  2003. title = QtWidgets.QLabel(
  2004. "<font size=8><B>FlatCAM</B></font><BR>"
  2005. "Version %s %s (%s) - %s <BR>"
  2006. "<BR>"
  2007. "2D Computer-Aided Printed Circuit Board<BR>"
  2008. "Manufacturing.<BR>"
  2009. "<BR>"
  2010. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2011. "<BR>"
  2012. "<B> Main Contributors:</B><BR>"
  2013. "Denis Hayrullin<BR>"
  2014. "Kamil Sopko<BR>"
  2015. "Marius Stanciu<BR>"
  2016. "Matthieu Berthomé<BR>"
  2017. "and many others found "
  2018. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2019. "<BR>"
  2020. "Development is done "
  2021. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2022. "DOWNLOAD area "
  2023. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2024. "" % (version, ('BETA' if beta else ''), version_date, platform.architecture()[0])
  2025. )
  2026. title.setOpenExternalLinks(True)
  2027. layout2.addWidget(title, stretch=1)
  2028. layout3 = QtWidgets.QHBoxLayout()
  2029. layout1.addLayout(layout3)
  2030. layout3.addStretch()
  2031. okbtn = QtWidgets.QPushButton("Close")
  2032. layout3.addWidget(okbtn)
  2033. okbtn.clicked.connect(self.accept)
  2034. AboutDialog(self.ui).exec_()
  2035. def on_file_savedefaults(self):
  2036. """
  2037. Callback for menu item File->Save Defaults. Saves application default options
  2038. ``self.defaults`` to current_defaults.FlatConfig.
  2039. :return: None
  2040. """
  2041. self.save_defaults()
  2042. def on_app_exit(self):
  2043. self.report_usage("on_app_exit()")
  2044. if self.collection.get_list():
  2045. msgbox = QtWidgets.QMessageBox()
  2046. # msgbox.setText("<B>Save changes ...</B>")
  2047. msgbox.setText("There are files/objects opened in FlatCAM. "
  2048. "\n"
  2049. "Do you want to Save the project?")
  2050. msgbox.setWindowTitle("Save changes")
  2051. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2052. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2053. QtWidgets.QMessageBox.Cancel)
  2054. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2055. response = msgbox.exec_()
  2056. if response == QtWidgets.QMessageBox.Yes:
  2057. self.on_file_saveprojectas(thread=False)
  2058. elif response == QtWidgets.QMessageBox.Cancel:
  2059. return
  2060. self.save_defaults()
  2061. else:
  2062. self.save_defaults()
  2063. log.debug("Application defaults saved ... Exit event.")
  2064. QtWidgets.qApp.quit()
  2065. def save_defaults(self, silent=False):
  2066. """
  2067. Saves application default options
  2068. ``self.defaults`` to current_defaults.FlatConfig.
  2069. :return: None
  2070. """
  2071. self.report_usage("save_defaults")
  2072. # Read options from file
  2073. try:
  2074. f = open(self.data_path + "/current_defaults.FlatConfig")
  2075. defaults_file_content = f.read()
  2076. f.close()
  2077. except:
  2078. e = sys.exc_info()[0]
  2079. App.log.error("Could not load defaults file.")
  2080. App.log.error(str(e))
  2081. self.inform.emit("[ERROR_NOTCL] Could not load defaults file.")
  2082. return
  2083. try:
  2084. defaults = json.loads(defaults_file_content)
  2085. except:
  2086. e = sys.exc_info()[0]
  2087. App.log.error("Failed to parse defaults file.")
  2088. App.log.error(str(e))
  2089. self.inform.emit("[ERROR_NOTCL] Failed to parse defaults file.")
  2090. return
  2091. # Update options
  2092. self.defaults_read_form()
  2093. defaults.update(self.defaults)
  2094. self.propagate_defaults(silent=True)
  2095. # Save update options
  2096. try:
  2097. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  2098. json.dump(defaults, f)
  2099. f.close()
  2100. except:
  2101. self.inform.emit("[ERROR_NOTCL] Failed to write defaults to file.")
  2102. return
  2103. # Save the toolbar view
  2104. tb_status = 0
  2105. if self.ui.toolbarfile.isVisible():
  2106. tb_status += 1
  2107. if self.ui.toolbargeo.isVisible():
  2108. tb_status += 2
  2109. if self.ui.toolbarview.isVisible():
  2110. tb_status += 4
  2111. if self.ui.toolbartools.isVisible():
  2112. tb_status += 8
  2113. if self.ui.exc_edit_toolbar.isVisible():
  2114. tb_status += 16
  2115. if self.ui.geo_edit_toolbar.isVisible():
  2116. tb_status += 32
  2117. if self.ui.snap_toolbar.isVisible():
  2118. tb_status += 64
  2119. self.defaults["global_toolbar_view"] = tb_status
  2120. if not silent:
  2121. self.inform.emit("[success]Defaults saved.")
  2122. def save_factory_defaults(self, silent=False):
  2123. """
  2124. Saves application factory default options
  2125. ``self.defaults`` to factory_defaults.FlatConfig.
  2126. It's a one time job done just after the first install.
  2127. :return: None
  2128. """
  2129. self.report_usage("save_factory_defaults")
  2130. # Read options from file
  2131. try:
  2132. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2133. factory_defaults_file_content = f_f_def.read()
  2134. f_f_def.close()
  2135. except:
  2136. e = sys.exc_info()[0]
  2137. App.log.error("Could not load factory defaults file.")
  2138. App.log.error(str(e))
  2139. self.inform.emit("[ERROR_NOTCL] Could not load factory defaults file.")
  2140. return
  2141. try:
  2142. factory_defaults = json.loads(factory_defaults_file_content)
  2143. except:
  2144. e = sys.exc_info()[0]
  2145. App.log.error("Failed to parse factory defaults file.")
  2146. App.log.error(str(e))
  2147. self.inform.emit("[ERROR_NOTCL] Failed to parse factory defaults file.")
  2148. return
  2149. # Update options
  2150. self.defaults_read_form()
  2151. factory_defaults.update(self.defaults)
  2152. self.propagate_defaults(silent=True)
  2153. # Save update options
  2154. try:
  2155. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2156. json.dump(factory_defaults, f_f_def_s)
  2157. f_f_def_s.close()
  2158. except:
  2159. self.inform.emit("[ERROR_NOTCL] Failed to write factory defaults to file.")
  2160. return
  2161. if silent is False:
  2162. self.inform.emit("Factory defaults saved.")
  2163. def final_save(self):
  2164. if self.collection.get_list():
  2165. msgbox = QtWidgets.QMessageBox()
  2166. # msgbox.setText("<B>Save changes ...</B>")
  2167. msgbox.setText("There are files/objects opened in FlatCAM. "
  2168. "\n"
  2169. "Do you want to Save the project?")
  2170. msgbox.setWindowTitle("Save changes")
  2171. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2172. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2173. QtWidgets.QMessageBox.Cancel)
  2174. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2175. response = msgbox.exec_()
  2176. if response == QtWidgets.QMessageBox.Yes:
  2177. self.on_file_saveprojectas(thread=False)
  2178. elif response == QtWidgets.QMessageBox.Cancel:
  2179. self.should_we_quit = False
  2180. return
  2181. self.save_defaults()
  2182. log.debug("Application defaults saved ... Exit event.")
  2183. def on_toggle_shell(self):
  2184. """
  2185. toggle shell if is visible close it if closed open it
  2186. :return:
  2187. """
  2188. self.report_usage("on_toggle_shell()")
  2189. if self.ui.shell_dock.isVisible():
  2190. self.ui.shell_dock.hide()
  2191. else:
  2192. self.ui.shell_dock.show()
  2193. def on_edit_join(self, name=None):
  2194. """
  2195. Callback for Edit->Join. Joins the selected geometry objects into
  2196. a new one.
  2197. :return: None
  2198. """
  2199. self.report_usage("on_edit_join()")
  2200. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2201. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2202. tooldias = []
  2203. geo_type_list = []
  2204. objs = self.collection.get_selected()
  2205. for obj in objs:
  2206. geo_type_list.append(obj.multigeo)
  2207. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2208. if len(set(geo_type_list)) != 1:
  2209. self.inform.emit("[ERROR] Failed join. The Geometry objects are of different types.\n"
  2210. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2211. "convert from one to another and retry joining \n"
  2212. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2213. "the result may not be what was expected. \n"
  2214. "Check the generated GCODE.")
  2215. return
  2216. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2217. if True in geo_type_list:
  2218. def initialize(obj, app):
  2219. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2220. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2221. for v in obj.tools.values():
  2222. v['data']['name'] = obj_name_multi
  2223. self.new_object("geometry", obj_name_multi, initialize)
  2224. else:
  2225. def initialize(obj, app):
  2226. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2227. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2228. for v in obj.tools.values():
  2229. v['data']['name'] = obj_name_single
  2230. self.new_object("geometry", obj_name_single, initialize)
  2231. def on_edit_join_exc(self):
  2232. """
  2233. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2234. a new one.
  2235. :return: None
  2236. """
  2237. self.report_usage("on_edit_join_exc()")
  2238. objs = self.collection.get_selected()
  2239. for obj in objs:
  2240. if not isinstance(obj, FlatCAMExcellon):
  2241. self.inform.emit("[ERROR_NOTCL]Failed. Excellon joining works only on Excellon objects.")
  2242. return
  2243. def initialize(obj, app):
  2244. FlatCAMExcellon.merge(objs, obj)
  2245. self.new_object("excellon", 'Combo_Excellon', initialize)
  2246. def on_edit_join_grb(self):
  2247. """
  2248. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2249. a new one.
  2250. :return: None
  2251. """
  2252. self.report_usage("on_edit_join_grb()")
  2253. objs = self.collection.get_selected()
  2254. for obj in objs:
  2255. if not isinstance(obj, FlatCAMGerber):
  2256. self.inform.emit("[ERROR_NOTCL]Failed. Gerber joining works only on Gerber objects.")
  2257. return
  2258. def initialize(obj, app):
  2259. FlatCAMGerber.merge(objs, obj)
  2260. self.new_object("gerber", 'Combo_Gerber', initialize)
  2261. def on_convert_singlegeo_to_multigeo(self):
  2262. self.report_usage("on_convert_singlegeo_to_multigeo()")
  2263. obj = self.collection.get_active()
  2264. if obj is None:
  2265. self.inform.emit("[ERROR_NOTCL]Failed. Select a Geometry Object and try again.")
  2266. return
  2267. if not isinstance(obj, FlatCAMGeometry):
  2268. self.inform.emit("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s" % type(obj))
  2269. return
  2270. obj.multigeo = True
  2271. for tooluid, dict_value in obj.tools.items():
  2272. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2273. if not isinstance(obj.solid_geometry, list):
  2274. obj.solid_geometry = [obj.solid_geometry]
  2275. obj.solid_geometry[:] = []
  2276. obj.plot()
  2277. self.inform.emit("[success] A Geometry object was converted to MultiGeo type.")
  2278. def on_convert_multigeo_to_singlegeo(self):
  2279. self.report_usage("on_convert_multigeo_to_singlegeo()")
  2280. obj = self.collection.get_active()
  2281. if obj is None:
  2282. self.inform.emit("[ERROR_NOTCL]Failed. Select a Geometry Object and try again.")
  2283. return
  2284. if not isinstance(obj, FlatCAMGeometry):
  2285. self.inform.emit("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s" % type(obj))
  2286. return
  2287. obj.multigeo = False
  2288. total_solid_geometry = []
  2289. for tooluid, dict_value in obj.tools.items():
  2290. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2291. # clear the original geometry
  2292. dict_value['solid_geometry'][:] = []
  2293. obj.solid_geometry = deepcopy(total_solid_geometry)
  2294. obj.plot()
  2295. self.inform.emit("[success] A Geometry object was converted to SingleGeo type.")
  2296. def on_options_dict_change(self, field):
  2297. self.options_write_form_field(field)
  2298. if field == "units":
  2299. self.set_screen_units(self.options['units'])
  2300. def on_defaults_dict_change(self, field):
  2301. self.defaults_write_form_field(field)
  2302. def set_screen_units(self, units):
  2303. self.ui.units_label.setText("[" + self.options["units"].lower() + "]")
  2304. def on_toggle_units(self):
  2305. """
  2306. Callback for the Units radio-button change in the Options tab.
  2307. Changes the application's default units or the current project's units.
  2308. If changing the project's units, the change propagates to all of
  2309. the objects in the project.
  2310. :return: None
  2311. """
  2312. self.report_usage("on_toggle_units")
  2313. if self.toggle_units_ignore:
  2314. return
  2315. # If option is the same, then ignore
  2316. if self.general_options_form.general_app_group.units_radio.get_value().upper() == self.options["units"].upper():
  2317. self.log.debug("on_toggle_units(): Same as options, so ignoring.")
  2318. return
  2319. # Options to scale
  2320. dimensions = ['gerber_isotooldia', 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2321. 'gerber_noncoppermargin', 'gerber_bboxmargin','gerber_isooverlap','tools_nccoverlap',
  2322. 'tools_nccmargin','tools_cutouttooldia','tools_cutoutgapsize',
  2323. 'gerber_noncoppermargin','gerber_bboxmargin',
  2324. 'excellon_drillz', "excellon_toolchangexy",
  2325. 'excellon_travelz', 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2326. 'excellon_tooldia', 'excellon_endz', 'cncjob_tooldia',
  2327. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate', 'geometry_feedrate_rapid',
  2328. 'geometry_cnctooldia', 'tools_painttooldia', 'tools_paintoverlap', 'geometry_toolchangexy',
  2329. 'geometry_toolchangez',
  2330. 'tools_paintmargin', 'geometry_endz', 'geometry_depthperpass', 'global_gridx', 'global_gridy']
  2331. def scale_options(sfactor):
  2332. for dim in dimensions:
  2333. if dim == 'excellon_toolchangexy':
  2334. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2335. coords_xy[0] *= sfactor
  2336. coords_xy[1] *= sfactor
  2337. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2338. elif dim == 'geometry_toolchangexy':
  2339. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2340. coords_xy[0] *= sfactor
  2341. coords_xy[1] *= sfactor
  2342. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2343. else:
  2344. self.options[dim] *= sfactor
  2345. # The scaling factor depending on choice of units.
  2346. factor = 1/25.4
  2347. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2348. factor = 25.4
  2349. # Changing project units. Warn user.
  2350. msgbox = QtWidgets.QMessageBox()
  2351. msgbox.setText("<B>Change project units ...</B>")
  2352. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  2353. "properties of all objects to be scaled accordingly. Continue?")
  2354. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Ok)
  2355. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2356. response = msgbox.exec_()
  2357. if response == QtWidgets.QMessageBox.Ok:
  2358. self.options_read_form()
  2359. scale_options(factor)
  2360. self.options_write_form()
  2361. # change this only if the workspace is active
  2362. if self.defaults['global_workspace'] is True:
  2363. self.plotcanvas.draw_workspace()
  2364. # adjust the grid values on the main toolbar
  2365. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  2366. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  2367. for obj in self.collection.get_list():
  2368. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  2369. obj.convert_units(units)
  2370. # make that the properties stored in the object are also updated
  2371. self.object_changed.emit(obj)
  2372. obj.build_ui()
  2373. current = self.collection.get_active()
  2374. if current is not None:
  2375. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  2376. if not isinstance(current, FlatCAMGeometry):
  2377. current.to_form()
  2378. self.plot_all()
  2379. self.inform.emit("[success]Converted units to %s" % self.options["units"])
  2380. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  2381. self.set_screen_units(self.options["units"])
  2382. else:
  2383. # Undo toggling
  2384. self.toggle_units_ignore = True
  2385. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2386. self.general_options_form.general_app_group.units_radio.set_value('IN')
  2387. else:
  2388. self.general_options_form.general_app_group.units_radio.set_value('MM')
  2389. self.toggle_units_ignore = False
  2390. self.inform.emit("[WARNING_NOTCL]Units conversion cancelled.")
  2391. self.options_read_form()
  2392. def on_toggle_units_click(self):
  2393. if self.options["units"] == 'MM':
  2394. self.general_options_form.general_app_group.units_radio.set_value("IN")
  2395. else:
  2396. self.general_options_form.general_app_group.units_radio.set_value("MM")
  2397. self.on_toggle_units()
  2398. def on_language_apply(self):
  2399. self.report_usage("on_language_apply()")
  2400. # TODO: apply the language
  2401. # app restart section
  2402. pass
  2403. def on_fullscreen(self):
  2404. self.report_usage("on_fullscreen()")
  2405. if self.toggle_fscreen is False:
  2406. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  2407. tb.setVisible(False)
  2408. self.ui.splitter_left.setVisible(False)
  2409. self.toggle_fscreen = True
  2410. else:
  2411. self.restore_toolbar_view()
  2412. self.ui.splitter_left.setVisible(True)
  2413. self.toggle_fscreen = False
  2414. def on_toggle_plotarea(self):
  2415. self.report_usage("on_toggle_plotarea()")
  2416. try:
  2417. name = self.ui.plot_tab_area.widget(0).objectName()
  2418. except AttributeError:
  2419. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  2420. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2421. self.ui.plot_tab_area.protectTab(0)
  2422. return
  2423. if name != 'plotarea':
  2424. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  2425. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2426. self.ui.plot_tab_area.protectTab(0)
  2427. else:
  2428. self.ui.plot_tab_area.closeTab(0)
  2429. def on_toggle_notebook(self):
  2430. if self.ui.splitter.sizes()[0] == 0:
  2431. self.ui.splitter.setSizes([1, 1])
  2432. else:
  2433. self.ui.splitter.setSizes([0, 1])
  2434. def on_toggle_axis(self):
  2435. self.report_usage("on_toggle_axis()")
  2436. if self.toggle_axis is False:
  2437. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2438. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2439. self.plotcanvas.redraw()
  2440. self.toggle_axis = True
  2441. else:
  2442. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2443. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2444. self.plotcanvas.redraw()
  2445. self.toggle_axis = False
  2446. def on_toggle_grid(self):
  2447. self.report_usage("on_toggle_grid()")
  2448. self.ui.grid_snap_btn.trigger()
  2449. def on_options_combo_change(self, sel):
  2450. """
  2451. Called when the combo box to choose between application defaults and
  2452. project option changes value. The corresponding variables are
  2453. copied to the UI.
  2454. :param sel: The option index that was chosen.
  2455. :return: None
  2456. """
  2457. # combo_sel = self.ui.notebook.combo_options.get_active()
  2458. App.log.debug("Options --> %s" % sel)
  2459. # form = [self.defaults_form, self.options_form][sel]
  2460. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  2461. if sel == 0:
  2462. self.gen_form = self.general_defaults_form
  2463. self.ger_form = self.gerber_defaults_form
  2464. self.exc_form = self.excellon_defaults_form
  2465. self.geo_form = self.geometry_defaults_form
  2466. self.cnc_form = self.cncjob_defaults_form
  2467. self.tools_form = self.tools_defaults_form
  2468. elif sel == 1:
  2469. self.gen_form = self.general_options_form
  2470. self.ger_form = self.gerber_options_form
  2471. self.exc_form = self.excellon_options_form
  2472. self.geo_form = self.geometry_options_form
  2473. self.cnc_form = self.cncjob_options_form
  2474. self.tools_form = self.tools_options_form
  2475. else:
  2476. return
  2477. try:
  2478. self.ui.general_scroll_area.takeWidget()
  2479. except:
  2480. self.log.debug("Nothing to remove")
  2481. self.ui.general_scroll_area.setWidget(self.gen_form)
  2482. self.gen_form.show()
  2483. try:
  2484. self.ui.gerber_scroll_area.takeWidget()
  2485. except:
  2486. self.log.debug("Nothing to remove")
  2487. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  2488. self.ger_form.show()
  2489. try:
  2490. self.ui.excellon_scroll_area.takeWidget()
  2491. except:
  2492. self.log.debug("Nothing to remove")
  2493. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  2494. self.exc_form.show()
  2495. try:
  2496. self.ui.geometry_scroll_area.takeWidget()
  2497. except:
  2498. self.log.debug("Nothing to remove")
  2499. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  2500. self.geo_form.show()
  2501. try:
  2502. self.ui.cncjob_scroll_area.takeWidget()
  2503. except:
  2504. self.log.debug("Nothing to remove")
  2505. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  2506. self.cnc_form.show()
  2507. try:
  2508. self.ui.tools_scroll_area.takeWidget()
  2509. except:
  2510. self.log.debug("Nothing to remove")
  2511. self.ui.tools_scroll_area.setWidget(self.tools_form)
  2512. self.tools_form.show()
  2513. self.log.debug("Finished GUI form initialization.")
  2514. # self.options2form()
  2515. def on_excellon_defaults_button(self):
  2516. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  2517. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  2518. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  2519. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  2520. self.defaults_form_fields["excellon_zeros"].set_value('L')
  2521. self.defaults_form_fields["excellon_units"].set_value('INCH')
  2522. log.debug("Excellon app defaults loaded ...")
  2523. def on_excellon_options_button(self):
  2524. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  2525. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  2526. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  2527. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  2528. self.options_form_fields["excellon_zeros"].set_value('L')
  2529. self.options_form_fields["excellon_units"].set_value('INCH')
  2530. log.debug("Excellon options defaults loaded ...")
  2531. # Setting plot colors handlers
  2532. def on_pf_color_entry(self):
  2533. self.defaults['global_plot_fill'] = self.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  2534. self.defaults['global_plot_fill'][7:9]
  2535. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2536. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  2537. def on_pf_color_button(self):
  2538. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  2539. c_dialog = QtWidgets.QColorDialog()
  2540. plot_fill_color = c_dialog.getColor(initial=current_color)
  2541. if plot_fill_color.isValid() is False:
  2542. return
  2543. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2544. "background-color:%s" % str(plot_fill_color.name()))
  2545. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  2546. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  2547. self.defaults['global_plot_fill'] = new_val
  2548. def on_pf_color_spinner(self):
  2549. spinner_value = self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  2550. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  2551. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  2552. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2553. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  2554. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2555. def on_pf_color_slider(self):
  2556. slider_value = self.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  2557. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  2558. def on_pl_color_entry(self):
  2559. self.defaults['global_plot_line'] = self.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  2560. self.defaults['global_plot_line'][7:9]
  2561. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2562. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  2563. def on_pl_color_button(self):
  2564. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  2565. # print(current_color)
  2566. c_dialog = QtWidgets.QColorDialog()
  2567. plot_line_color = c_dialog.getColor(initial=current_color)
  2568. if plot_line_color.isValid() is False:
  2569. return
  2570. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2571. "background-color:%s" % str(plot_line_color.name()))
  2572. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  2573. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  2574. self.defaults['global_plot_line'] = new_val_line
  2575. # Setting selection colors (left - right) handlers
  2576. def on_sf_color_entry(self):
  2577. self.defaults['global_sel_fill'] = self.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  2578. self.defaults['global_sel_fill'][7:9]
  2579. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2580. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  2581. def on_sf_color_button(self):
  2582. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  2583. c_dialog = QtWidgets.QColorDialog()
  2584. plot_fill_color = c_dialog.getColor(initial=current_color)
  2585. if plot_fill_color.isValid() is False:
  2586. return
  2587. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2588. "background-color:%s" % str(plot_fill_color.name()))
  2589. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  2590. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  2591. self.defaults['global_sel_fill'] = new_val
  2592. def on_sf_color_spinner(self):
  2593. spinner_value = self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  2594. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  2595. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  2596. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2597. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  2598. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2599. def on_sf_color_slider(self):
  2600. slider_value = self.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  2601. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  2602. def on_sl_color_entry(self):
  2603. self.defaults['global_sel_line'] = self.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  2604. self.defaults['global_sel_line'][7:9]
  2605. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2606. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  2607. def on_sl_color_button(self):
  2608. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  2609. c_dialog = QtWidgets.QColorDialog()
  2610. plot_line_color = c_dialog.getColor(initial=current_color)
  2611. if plot_line_color.isValid() is False:
  2612. return
  2613. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2614. "background-color:%s" % str(plot_line_color.name()))
  2615. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  2616. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  2617. self.defaults['global_sel_line'] = new_val_line
  2618. # Setting selection colors (right - left) handlers
  2619. def on_alt_sf_color_entry(self):
  2620. self.defaults['global_alt_sel_fill'] = self.general_defaults_form.general_gui_group \
  2621. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  2622. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2623. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  2624. def on_alt_sf_color_button(self):
  2625. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  2626. c_dialog = QtWidgets.QColorDialog()
  2627. plot_fill_color = c_dialog.getColor(initial=current_color)
  2628. if plot_fill_color.isValid() is False:
  2629. return
  2630. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2631. "background-color:%s" % str(plot_fill_color.name()))
  2632. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  2633. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  2634. self.defaults['global_alt_sel_fill'] = new_val
  2635. def on_alt_sf_color_spinner(self):
  2636. spinner_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  2637. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  2638. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  2639. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2640. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  2641. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2642. def on_alt_sf_color_slider(self):
  2643. slider_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  2644. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  2645. def on_alt_sl_color_entry(self):
  2646. self.defaults['global_alt_sel_line'] = self.general_defaults_form.general_gui_group \
  2647. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  2648. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2649. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  2650. def on_alt_sl_color_button(self):
  2651. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  2652. c_dialog = QtWidgets.QColorDialog()
  2653. plot_line_color = c_dialog.getColor(initial=current_color)
  2654. if plot_line_color.isValid() is False:
  2655. return
  2656. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2657. "background-color:%s" % str(plot_line_color.name()))
  2658. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  2659. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  2660. self.defaults['global_alt_sel_line'] = new_val_line
  2661. # Setting Editor colors
  2662. def on_draw_color_entry(self):
  2663. self.defaults['global_draw_color'] = self.general_defaults_form.general_gui_group \
  2664. .draw_color_entry.get_value()
  2665. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2666. "background-color:%s" % str(self.defaults['global_draw_color']))
  2667. def on_draw_color_button(self):
  2668. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  2669. c_dialog = QtWidgets.QColorDialog()
  2670. draw_color = c_dialog.getColor(initial=current_color)
  2671. if draw_color.isValid() is False:
  2672. return
  2673. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2674. "background-color:%s" % str(draw_color.name()))
  2675. new_val = str(draw_color.name())
  2676. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  2677. self.defaults['global_draw_color'] = new_val
  2678. def on_sel_draw_color_entry(self):
  2679. self.defaults['global_sel_draw_color'] = self.general_defaults_form.general_gui_group \
  2680. .sel_draw_color_entry.get_value()
  2681. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2682. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  2683. def on_sel_draw_color_button(self):
  2684. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  2685. c_dialog = QtWidgets.QColorDialog()
  2686. sel_draw_color = c_dialog.getColor(initial=current_color)
  2687. if sel_draw_color.isValid() is False:
  2688. return
  2689. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2690. "background-color:%s" % str(sel_draw_color.name()))
  2691. new_val_sel = str(sel_draw_color.name())
  2692. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  2693. self.defaults['global_sel_draw_color'] = new_val_sel
  2694. def on_deselect_all(self):
  2695. self.collection.set_all_inactive()
  2696. self.delete_selection_shape()
  2697. def on_workspace_modified(self):
  2698. self.save_defaults(silent=True)
  2699. self.plotcanvas.draw_workspace()
  2700. def on_workspace(self):
  2701. self.report_usage("on_workspace()")
  2702. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2703. self.plotcanvas.restore_workspace()
  2704. else:
  2705. self.plotcanvas.delete_workspace()
  2706. self.save_defaults(silent=True)
  2707. def on_workspace_menu(self):
  2708. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2709. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  2710. else:
  2711. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  2712. self.on_workspace()
  2713. def on_layout(self):
  2714. self.report_usage("on_layout()")
  2715. current_layout= self.general_defaults_form.general_gui_group.layout_combo.get_value().lower()
  2716. settings = QSettings("Open Source", "FlatCAM")
  2717. settings.setValue('layout', current_layout)
  2718. # This will write the setting to the platform specific storage.
  2719. del settings
  2720. # first remove the toolbars:
  2721. self.ui.removeToolBar(self.ui.toolbarfile)
  2722. self.ui.removeToolBar(self.ui.toolbargeo)
  2723. self.ui.removeToolBar(self.ui.toolbarview)
  2724. self.ui.removeToolBar(self.ui.toolbartools)
  2725. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  2726. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  2727. self.ui.removeToolBar(self.ui.snap_toolbar)
  2728. if current_layout == 'standard':
  2729. ### TOOLBAR INSTALLATION ###
  2730. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  2731. self.ui.toolbarfile.setObjectName('File_TB')
  2732. self.ui.addToolBar(self.ui.toolbarfile)
  2733. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  2734. self.ui.toolbargeo.setObjectName('Edit_TB')
  2735. self.ui.addToolBar(self.ui.toolbargeo)
  2736. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  2737. self.ui.toolbarview.setObjectName('View_TB')
  2738. self.ui.addToolBar(self.ui.toolbarview)
  2739. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  2740. self.ui.toolbartools.setObjectName('Tools_TB')
  2741. self.ui.addToolBar(self.ui.toolbartools)
  2742. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  2743. self.ui.exc_edit_toolbar.setVisible(False)
  2744. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  2745. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  2746. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  2747. self.ui.geo_edit_toolbar.setVisible(False)
  2748. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  2749. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  2750. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  2751. self.ui.snap_toolbar.setObjectName('Snap_TB')
  2752. # self.ui.snap_toolbar.setMaximumHeight(30)
  2753. self.ui.addToolBar(self.ui.snap_toolbar)
  2754. self.ui.corner_snap_btn.setVisible(False)
  2755. self.ui.snap_magnet.setVisible(False)
  2756. elif current_layout == 'compact':
  2757. ### TOOLBAR INSTALLATION ###
  2758. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  2759. self.ui.toolbarfile.setObjectName('File_TB')
  2760. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  2761. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  2762. self.ui.toolbargeo.setObjectName('Edit_TB')
  2763. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  2764. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  2765. self.ui.toolbarview.setObjectName('View_TB')
  2766. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  2767. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  2768. self.ui.toolbartools.setObjectName('Tools_TB')
  2769. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  2770. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  2771. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  2772. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.exc_edit_toolbar)
  2773. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  2774. self.ui.geo_edit_toolbar.setVisible(False)
  2775. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  2776. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  2777. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  2778. self.ui.snap_toolbar.setObjectName('Snap_TB')
  2779. self.ui.snap_toolbar.setMaximumHeight(30)
  2780. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  2781. self.ui.corner_snap_btn.setVisible(True)
  2782. self.ui.snap_magnet.setVisible(True)
  2783. self.ui.populate_toolbars()
  2784. self.ui.grid_snap_btn.setChecked(True)
  2785. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  2786. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  2787. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  2788. self.ui.grid_gap_link_cb.setChecked(True)
  2789. def on_save_button(self):
  2790. self.save_defaults(silent=False)
  2791. # load the defaults so they are updated into the app
  2792. self.load_defaults(filename='current_defaults')
  2793. # Re-fresh project options
  2794. self.on_options_app2project()
  2795. def handleOpen(self):
  2796. self.report_usage("handleOpen()")
  2797. filter_group = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2798. "All Files (*.*)"
  2799. path, _ = QtWidgets.QFileDialog.getOpenFileName(
  2800. caption='Open file', directory=self.get_last_folder(), filter=filter_group)
  2801. if path:
  2802. file = QtCore.QFile(path)
  2803. if file.open(QtCore.QIODevice.ReadOnly):
  2804. stream = QtCore.QTextStream(file)
  2805. self.gcode_edited = stream.readAll()
  2806. self.ui.code_editor.setPlainText(self.gcode_edited)
  2807. file.close()
  2808. def handlePrint(self):
  2809. self.report_usage("handlePrint()")
  2810. dialog = QtPrintSupport.QPrintDialog()
  2811. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  2812. self.ui.code_editor.document().print_(dialog.printer())
  2813. def handlePreview(self):
  2814. self.report_usage("handlePreview()")
  2815. dialog = QtPrintSupport.QPrintPreviewDialog()
  2816. dialog.paintRequested.connect(self.ui.code_editor.print_)
  2817. dialog.exec_()
  2818. def handleTextChanged(self):
  2819. self.report_usage("handleTextChanged()")
  2820. # enable = not self.ui.code_editor.document().isEmpty()
  2821. # self.ui.buttonPrint.setEnabled(enable)
  2822. # self.ui.buttonPreview.setEnabled(enable)
  2823. pass
  2824. def handleSaveGCode(self):
  2825. self.report_usage("handleSaveGCode()")
  2826. obj_name = self.collection.get_active().options['name']
  2827. _filter_ = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2828. "All Files (*.*)"
  2829. try:
  2830. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  2831. caption="Export G-Code ...",
  2832. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  2833. filter=_filter_
  2834. )[0])
  2835. except TypeError:
  2836. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption="Export G-Code ...", filter=_filter_)[0])
  2837. if filename == "":
  2838. self.inform.emit("[WARNING_NOTCL]Export CNC Code cancelled.")
  2839. return
  2840. else:
  2841. try:
  2842. my_gcode = self.ui.code_editor.toPlainText()
  2843. with open(filename, 'w') as f:
  2844. for line in my_gcode:
  2845. f.write(line)
  2846. except FileNotFoundError:
  2847. self.inform.emit("[WARNING] No such file or directory")
  2848. return
  2849. # Just for adding it to the recent files list.
  2850. self.file_opened.emit("cncjob", filename)
  2851. self.file_saved.emit("cncjob", filename)
  2852. self.inform.emit("Saved to: " + filename)
  2853. def handleFindGCode(self):
  2854. self.report_usage("handleFindGCode()")
  2855. flags = QtGui.QTextDocument.FindCaseSensitively
  2856. text_to_be_found = self.ui.entryFind.get_value()
  2857. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  2858. if r is False:
  2859. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2860. def handleReplaceGCode(self):
  2861. self.report_usage("handleReplaceGCode()")
  2862. old = self.ui.entryFind.get_value()
  2863. new = self.ui.entryReplace.get_value()
  2864. if self.ui.sel_all_cb.isChecked():
  2865. while True:
  2866. cursor = self.ui.code_editor.textCursor()
  2867. cursor.beginEditBlock()
  2868. flags = QtGui.QTextDocument.FindCaseSensitively
  2869. # self.ui.editor is the QPlainTextEdit
  2870. r = self.ui.code_editor.find(str(old), flags)
  2871. if r:
  2872. qc = self.ui.code_editor.textCursor()
  2873. if qc.hasSelection():
  2874. qc.insertText(new)
  2875. else:
  2876. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2877. break
  2878. # Mark end of undo block
  2879. cursor.endEditBlock()
  2880. else:
  2881. cursor = self.ui.code_editor.textCursor()
  2882. cursor.beginEditBlock()
  2883. qc = self.ui.code_editor.textCursor()
  2884. if qc.hasSelection():
  2885. qc.insertText(new)
  2886. # Mark end of undo block
  2887. cursor.endEditBlock()
  2888. def on_tool_add_keypress(self):
  2889. ## Current application units in Upper Case
  2890. self.units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  2891. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  2892. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  2893. if notebook_widget_name == 'selected_tab':
  2894. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  2895. tool_add_popup = FCInputDialog(title="New Tool ...",
  2896. text='Enter a Tool Diameter:',
  2897. min=0.0000, max=99.9999, decimals=4)
  2898. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  2899. val, ok = tool_add_popup.get_value()
  2900. if ok:
  2901. if float(val) == 0:
  2902. self.inform.emit(
  2903. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  2904. return
  2905. self.collection.get_active().on_tool_add(dia=float(val))
  2906. else:
  2907. self.inform.emit(
  2908. "[WARNING_NOTCL] Adding Tool cancelled ...")
  2909. # work only if the notebook tab on focus is the Tools_Tab
  2910. if notebook_widget_name == 'tool_tab':
  2911. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  2912. # and only if the tool is NCC Tool
  2913. if tool_widget == self.ncclear_tool.toolName:
  2914. tool_add_popup = FCInputDialog(title="New Tool ...",
  2915. text='Enter a Tool Diameter:',
  2916. min=0.0000, max=99.9999, decimals=4)
  2917. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  2918. val, ok = tool_add_popup.get_value()
  2919. if ok:
  2920. if float(val) == 0:
  2921. self.inform.emit(
  2922. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  2923. return
  2924. self.ncclear_tool.on_tool_add(dia=float(val))
  2925. else:
  2926. self.inform.emit(
  2927. "[WARNING_NOTCL] Adding Tool cancelled ...")
  2928. # and only if the tool is Paint Area Tool
  2929. elif tool_widget == self.paint_tool.toolName:
  2930. tool_add_popup = FCInputDialog(title="New Tool ...",
  2931. text='Enter a Tool Diameter:',
  2932. min=0.0000, max=99.9999, decimals=4)
  2933. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  2934. val, ok = tool_add_popup.get_value()
  2935. if ok:
  2936. if float(val) == 0:
  2937. self.inform.emit(
  2938. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  2939. return
  2940. self.paint_tool.on_tool_add(dia=float(val))
  2941. else:
  2942. self.inform.emit(
  2943. "[WARNING_NOTCL] Adding Tool cancelled ...")
  2944. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  2945. # See description bellow.
  2946. def on_delete_keypress(self):
  2947. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  2948. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  2949. if notebook_widget_name == 'selected_tab':
  2950. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  2951. self.collection.get_active().on_tool_delete()
  2952. # work only if the notebook tab on focus is the Tools_Tab
  2953. elif notebook_widget_name == 'tool_tab':
  2954. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  2955. # and only if the tool is NCC Tool
  2956. if tool_widget == self.ncclear_tool.toolName:
  2957. self.ncclear_tool.on_tool_delete()
  2958. # and only if the tool is Paint Tool
  2959. elif tool_widget == self.paint_tool.toolName:
  2960. self.paint_tool.on_tool_delete()
  2961. else:
  2962. self.on_delete()
  2963. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  2964. # some screens you have to be careful where you hover with your mouse.
  2965. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  2966. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  2967. # Complicated, I know :)
  2968. def on_delete(self):
  2969. """
  2970. Delete the currently selected FlatCAMObjs.
  2971. :return: None
  2972. """
  2973. self.report_usage("on_delete()")
  2974. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  2975. # a geometry object before we update it.
  2976. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  2977. if self.collection.get_active():
  2978. self.log.debug("on_delete()")
  2979. self.report_usage("on_delete")
  2980. while (self.collection.get_active()):
  2981. self.delete_first_selected()
  2982. self.inform.emit("Object(s) deleted ...")
  2983. # make sure that the selection shape is deleted, too
  2984. self.delete_selection_shape()
  2985. else:
  2986. self.inform.emit("Failed. No object(s) selected...")
  2987. else:
  2988. self.inform.emit("Save the work in Editor and try again ...")
  2989. def on_set_origin(self):
  2990. """
  2991. Set the origin to the left mouse click position
  2992. :return: None
  2993. """
  2994. #display the message for the user
  2995. #and ask him to click on the desired position
  2996. self.report_usage("on_set_origin()")
  2997. self.inform.emit('Click to set the origin ...')
  2998. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  2999. def on_jump_to(self):
  3000. """
  3001. Jump to a location by setting the mouse cursor location
  3002. :return:
  3003. """
  3004. self.report_usage("on_jump_to()")
  3005. dia_box = Dialog_box(title="Jump to Coordinates", label="Enter the coordinates in format X,Y:")
  3006. if dia_box.ok is True:
  3007. try:
  3008. location = eval(dia_box.location)
  3009. if not isinstance(location, tuple):
  3010. self.inform.emit("Wrong coordinates. Enter coordinates in format: X,Y")
  3011. return
  3012. except:
  3013. return
  3014. else:
  3015. return
  3016. self.plotcanvas.fit_center(loc=location)
  3017. cursor = QtGui.QCursor()
  3018. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3019. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  3020. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  3021. self.inform.emit("Done.")
  3022. def on_copy_object(self):
  3023. self.report_usage("on_copy_object()")
  3024. def initialize(obj_init, app):
  3025. obj_init.solid_geometry = obj.solid_geometry
  3026. try:
  3027. if obj.tools:
  3028. obj_init.tools = obj.tools
  3029. except Exception as e:
  3030. log.debug("on_copy_object() --> %s" % str(e))
  3031. def initialize_excellon(obj_init, app):
  3032. obj_init.tools = obj.tools
  3033. # drills are offset, so they need to be deep copied
  3034. obj_init.drills = deepcopy(obj.drills)
  3035. # slots are offset, so they need to be deep copied
  3036. obj_init.slots = deepcopy(obj.slots)
  3037. obj_init.create_geometry()
  3038. for obj in self.collection.get_selected():
  3039. obj_name = obj.options["name"]
  3040. try:
  3041. if isinstance(obj, FlatCAMExcellon):
  3042. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3043. elif isinstance(obj,FlatCAMGerber):
  3044. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  3045. elif isinstance(obj,FlatCAMGeometry):
  3046. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  3047. except Exception as e:
  3048. return "Operation failed: %s" % str(e)
  3049. def on_copy_object2(self, custom_name):
  3050. def initialize_geometry(obj_init, app):
  3051. obj_init.solid_geometry = obj.solid_geometry
  3052. try:
  3053. if obj.tools:
  3054. obj_init.tools = obj.tools
  3055. except Exception as e:
  3056. log.debug("on_copy_object2() --> %s" % str(e))
  3057. def initialize_gerber(obj_init, app):
  3058. obj_init.solid_geometry = obj.solid_geometry
  3059. obj_init.apertures = deepcopy(obj.apertures)
  3060. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3061. def initialize_excellon(obj_init, app):
  3062. obj_init.tools = obj.tools
  3063. # drills are offset, so they need to be deep copied
  3064. obj_init.drills = deepcopy(obj.drills)
  3065. # slots are offset, so they need to be deep copied
  3066. obj_init.slots = deepcopy(obj.slots)
  3067. obj_init.create_geometry()
  3068. for obj in self.collection.get_selected():
  3069. obj_name = obj.options["name"]
  3070. try:
  3071. if isinstance(obj, FlatCAMExcellon):
  3072. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  3073. elif isinstance(obj,FlatCAMGerber):
  3074. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  3075. elif isinstance(obj,FlatCAMGeometry):
  3076. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  3077. except Exception as e:
  3078. return "Operation failed: %s" % str(e)
  3079. def on_rename_object(self, text):
  3080. self.report_usage("on_rename_object()")
  3081. named_obj = self.collection.get_active()
  3082. for obj in named_obj:
  3083. if obj is list:
  3084. self.on_rename_object(text)
  3085. else:
  3086. try:
  3087. obj.options['name'] = text
  3088. except:
  3089. log.warning("Could not rename the object in the list")
  3090. def on_copy_object_as_geometry(self):
  3091. self.report_usage("on_copy_object_as_geometry()")
  3092. def initialize(obj_init, app):
  3093. obj_init.solid_geometry = obj.solid_geometry
  3094. if obj.tools:
  3095. obj_init.tools = obj.tools
  3096. def initialize_excellon(obj, app):
  3097. objs = self.collection.get_selected()
  3098. FlatCAMGeometry.merge(objs, obj)
  3099. for obj in self.collection.get_selected():
  3100. obj_name = obj.options["name"]
  3101. try:
  3102. if isinstance(obj, FlatCAMExcellon):
  3103. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  3104. else:
  3105. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  3106. except Exception as e:
  3107. return "Operation failed: %s" % str(e)
  3108. def on_set_zero_click(self, event):
  3109. #this function will be available only for mouse left click
  3110. pos =[]
  3111. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3112. if event.button == 1:
  3113. if self.grid_status() == True:
  3114. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3115. else:
  3116. pos = pos_canvas
  3117. x = 0 - pos[0]
  3118. y = 0 - pos[1]
  3119. for obj in self.collection.get_list():
  3120. obj.offset((x,y))
  3121. self.object_changed.emit(obj)
  3122. # obj.plot()
  3123. self.plot_all(zoom=False)
  3124. self.inform.emit('[success] Origin set ...')
  3125. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  3126. def on_selectall(self):
  3127. self.report_usage("on_selectall()")
  3128. # delete the possible selection box around a possible selected object
  3129. self.delete_selection_shape()
  3130. for name in self.collection.get_names():
  3131. self.collection.set_active(name)
  3132. curr_sel_obj = self.collection.get_by_name(name)
  3133. # create the selection box around the selected object
  3134. self.draw_selection_shape(curr_sel_obj)
  3135. def on_preferences(self):
  3136. # add the tab if it was closed
  3137. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, "Preferences")
  3138. # delete the absolute and relative position and messages in the infobar
  3139. self.ui.position_label.setText("")
  3140. self.ui.rel_position_label.setText("")
  3141. # Switch plot_area to preferences page
  3142. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  3143. self.ui.show()
  3144. def on_flipy(self):
  3145. self.report_usage("on_flipy()")
  3146. obj_list = self.collection.get_selected()
  3147. xminlist = []
  3148. yminlist = []
  3149. xmaxlist = []
  3150. ymaxlist = []
  3151. if not obj_list:
  3152. self.inform.emit("[WARNING_NOTCL] No object selected to Flip on Y axis.")
  3153. else:
  3154. try:
  3155. # first get a bounding box to fit all
  3156. for obj in obj_list:
  3157. xmin, ymin, xmax, ymax = obj.bounds()
  3158. xminlist.append(xmin)
  3159. yminlist.append(ymin)
  3160. xmaxlist.append(xmax)
  3161. ymaxlist.append(ymax)
  3162. # get the minimum x,y and maximum x,y for all objects selected
  3163. xminimal = min(xminlist)
  3164. yminimal = min(yminlist)
  3165. xmaximal = max(xmaxlist)
  3166. ymaximal = max(ymaxlist)
  3167. px = 0.5 * (xminimal + xmaximal)
  3168. py = 0.5 * (yminimal + ymaximal)
  3169. # execute mirroring
  3170. for obj in obj_list:
  3171. obj.mirror('X', [px, py])
  3172. obj.plot()
  3173. self.object_changed.emit(obj)
  3174. except Exception as e:
  3175. self.inform.emit("[ERROR_NOTCL] Due of %s, Flip action was not executed." % str(e))
  3176. return
  3177. def on_flipx(self):
  3178. self.report_usage("on_flipx()")
  3179. obj_list = self.collection.get_selected()
  3180. xminlist = []
  3181. yminlist = []
  3182. xmaxlist = []
  3183. ymaxlist = []
  3184. if not obj_list:
  3185. self.inform.emit("[WARNING_NOTCL] No object selected to Flip on X axis.")
  3186. else:
  3187. try:
  3188. # first get a bounding box to fit all
  3189. for obj in obj_list:
  3190. xmin, ymin, xmax, ymax = obj.bounds()
  3191. xminlist.append(xmin)
  3192. yminlist.append(ymin)
  3193. xmaxlist.append(xmax)
  3194. ymaxlist.append(ymax)
  3195. # get the minimum x,y and maximum x,y for all objects selected
  3196. xminimal = min(xminlist)
  3197. yminimal = min(yminlist)
  3198. xmaximal = max(xmaxlist)
  3199. ymaximal = max(ymaxlist)
  3200. px = 0.5 * (xminimal + xmaximal)
  3201. py = 0.5 * (yminimal + ymaximal)
  3202. # execute mirroring
  3203. for obj in obj_list:
  3204. obj.mirror('Y', [px, py])
  3205. obj.plot()
  3206. self.object_changed.emit(obj)
  3207. except Exception as e:
  3208. self.inform.emit("[ERROR_NOTCL] Due of %s, Flip action was not executed." % str(e))
  3209. return
  3210. def on_rotate(self, silent=False, preset=None):
  3211. self.report_usage("on_rotate()")
  3212. obj_list = self.collection.get_selected()
  3213. xminlist = []
  3214. yminlist = []
  3215. xmaxlist = []
  3216. ymaxlist = []
  3217. if not obj_list:
  3218. self.inform.emit("[WARNING_NOTCL] No object selected to Rotate.")
  3219. else:
  3220. if silent is False:
  3221. rotatebox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3222. min=-360, max=360, decimals=3)
  3223. num, ok = rotatebox.get_value()
  3224. else:
  3225. num = preset
  3226. ok = True
  3227. if ok:
  3228. try:
  3229. # first get a bounding box to fit all
  3230. for obj in obj_list:
  3231. xmin, ymin, xmax, ymax = obj.bounds()
  3232. xminlist.append(xmin)
  3233. yminlist.append(ymin)
  3234. xmaxlist.append(xmax)
  3235. ymaxlist.append(ymax)
  3236. # get the minimum x,y and maximum x,y for all objects selected
  3237. xminimal = min(xminlist)
  3238. yminimal = min(yminlist)
  3239. xmaximal = max(xmaxlist)
  3240. ymaximal = max(ymaxlist)
  3241. px = 0.5 * (xminimal + xmaximal)
  3242. py = 0.5 * (yminimal + ymaximal)
  3243. for sel_obj in obj_list:
  3244. sel_obj.rotate(-num, point=(px, py))
  3245. sel_obj.plot()
  3246. self.object_changed.emit(sel_obj)
  3247. except Exception as e:
  3248. self.inform.emit("[ERROR_NOTCL] Due of %s, rotation movement was not executed." % str(e))
  3249. return
  3250. def on_skewx(self):
  3251. self.report_usage("on_skewx()")
  3252. obj_list = self.collection.get_selected()
  3253. xminlist = []
  3254. yminlist = []
  3255. if not obj_list:
  3256. self.inform.emit("[WARNING_NOTCL] No object selected to Skew/Shear on X axis.")
  3257. else:
  3258. skewxbox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3259. min=-360, max=360, decimals=3)
  3260. num, ok = skewxbox.get_value()
  3261. if ok:
  3262. # first get a bounding box to fit all
  3263. for obj in obj_list:
  3264. xmin, ymin, xmax, ymax = obj.bounds()
  3265. xminlist.append(xmin)
  3266. yminlist.append(ymin)
  3267. # get the minimum x,y and maximum x,y for all objects selected
  3268. xminimal = min(xminlist)
  3269. yminimal = min(yminlist)
  3270. for obj in obj_list:
  3271. obj.skew(num, 0, point=(xminimal, yminimal))
  3272. obj.plot()
  3273. self.object_changed.emit(obj)
  3274. def on_skewy(self):
  3275. self.report_usage("on_skewy()")
  3276. obj_list = self.collection.get_selected()
  3277. xminlist = []
  3278. yminlist = []
  3279. if not obj_list:
  3280. self.inform.emit("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis.")
  3281. else:
  3282. skewybox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3283. min=-360, max=360, decimals=3)
  3284. num, ok = skewybox.get_value()
  3285. if ok:
  3286. # first get a bounding box to fit all
  3287. for obj in obj_list:
  3288. xmin, ymin, xmax, ymax = obj.bounds()
  3289. xminlist.append(xmin)
  3290. yminlist.append(ymin)
  3291. # get the minimum x,y and maximum x,y for all objects selected
  3292. xminimal = min(xminlist)
  3293. yminimal = min(yminlist)
  3294. for obj in obj_list:
  3295. obj.skew(0, num, point=(xminimal, yminimal))
  3296. obj.plot()
  3297. self.object_changed.emit(obj)
  3298. def delete_first_selected(self):
  3299. # Keep this for later
  3300. try:
  3301. name = self.collection.get_active().options["name"]
  3302. except AttributeError:
  3303. self.log.debug("Nothing selected for deletion")
  3304. return
  3305. # Remove plot
  3306. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3307. # self.plotcanvas.auto_adjust_axes()
  3308. # Clear form
  3309. self.setup_component_editor()
  3310. # Remove from dictionary
  3311. self.collection.delete_active()
  3312. self.inform.emit("Object deleted: %s" % name)
  3313. def on_plots_updated(self):
  3314. """
  3315. Callback used to report when the plots have changed.
  3316. Adjust axes and zooms to fit.
  3317. :return: None
  3318. """
  3319. # self.plotcanvas.auto_adjust_axes()
  3320. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  3321. self.on_zoom_fit(None)
  3322. # TODO: Rework toolbar 'clear', 'replot' functions
  3323. def on_toolbar_replot(self):
  3324. """
  3325. Callback for toolbar button. Re-plots all objects.
  3326. :return: None
  3327. """
  3328. self.report_usage("on_toolbar_replot")
  3329. self.log.debug("on_toolbar_replot()")
  3330. try:
  3331. self.collection.get_active().read_form()
  3332. except AttributeError:
  3333. self.log.debug("on_toolbar_replot(): AttributeError")
  3334. pass
  3335. self.plot_all()
  3336. def on_row_activated(self, index):
  3337. if index.isValid():
  3338. if index.internalPointer().parent_item != self.collection.root_item:
  3339. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3340. def grid_status(self):
  3341. if self.ui.grid_snap_btn.isChecked():
  3342. return 1
  3343. else:
  3344. return 0
  3345. # def on_key_over_plot(self, event):
  3346. # """
  3347. # Callback for the key pressed event when the canvas is focused. Keyboard
  3348. # shortcuts are handled here. So far, these are the shortcuts:
  3349. #
  3350. # ========== ============================================
  3351. # Key Action
  3352. # ========== ============================================
  3353. # '1' Zoom-fit. Fits the axes limits to the data.
  3354. # '2' Zoom-out.
  3355. # '3' Zoom-in.
  3356. # 'ctrl+m' Toggle on-off the measuring tool.
  3357. # ========== ============================================
  3358. #
  3359. # :param event: Ignored.
  3360. # :return: None
  3361. # """
  3362. # print(type(event.key), event.key)
  3363. # self.key_modifiers = QtWidgets.QApplication.keyboardModifiers()
  3364. #
  3365. # if self.key_modifiers == QtCore.Qt.ControlModifier:
  3366. # if event.key == 'A':
  3367. # self.on_selectall()
  3368. #
  3369. # if event.key == 'C':
  3370. # self.on_copy_object()
  3371. #
  3372. # if event.key == 'E':
  3373. # self.on_fileopenexcellon()
  3374. #
  3375. # if event.key == 'G':
  3376. # self.on_fileopengerber()
  3377. #
  3378. # if event.key == 'N':
  3379. # self.on_file_new_click()
  3380. #
  3381. # if event.key == 'M':
  3382. # self.measurement_tool.run()
  3383. #
  3384. # if event.key == 'O':
  3385. # self.on_file_openproject()
  3386. #
  3387. # if event.key == 'S':
  3388. # self.on_file_saveproject()
  3389. #
  3390. # # Toggle Plot Area
  3391. # if event.key == 'F10':
  3392. # self.on_toggle_plotarea()
  3393. #
  3394. # return
  3395. # elif self.key_modifiers == QtCore.Qt.AltModifier:
  3396. # # place holder for further shortcut key
  3397. #
  3398. # if event.key == '1':
  3399. # self.enable_all_plots()
  3400. #
  3401. # if event.key == '2':
  3402. # self.disable_all_plots()
  3403. #
  3404. # if event.key == '3':
  3405. # self.disable_other_plots()
  3406. #
  3407. # if event.key == 'C':
  3408. # self.calculator_tool.run()
  3409. #
  3410. # if event.key == 'D':
  3411. # self.dblsidedtool.run()
  3412. #
  3413. # if event.key == 'L':
  3414. # self.film_tool.run()
  3415. #
  3416. # if event.key == 'N':
  3417. # self.ncclear_tool.run()
  3418. #
  3419. # if event.key == 'P':
  3420. # self.paint_tool.run()
  3421. #
  3422. # if event.key == 'R':
  3423. # self.transform_tool.run()
  3424. #
  3425. # if event.key == 'U':
  3426. # self.cutout_tool.run()
  3427. #
  3428. # if event.key == 'Z':
  3429. # self.panelize_tool.run()
  3430. #
  3431. # if event.key == 'F10':
  3432. # self.on_fullscreen()
  3433. #
  3434. # return
  3435. # elif self.key_modifiers == QtCore.Qt.ShiftModifier:
  3436. # # place holder for further shortcut key
  3437. #
  3438. # if event.key == 'C':
  3439. # self.on_copy_name()
  3440. #
  3441. # # Toggle axis
  3442. # if event.key == 'G':
  3443. # self.on_toggle_axis()
  3444. #
  3445. # # Open Preferences Window
  3446. # if event.key == 'P':
  3447. # self.on_preferences()
  3448. #
  3449. # # Rotate Object by 90 degree CCW
  3450. # if event.key == 'R':
  3451. # self.on_rotate(silent=True, preset=-90)
  3452. #
  3453. # # Run a Script
  3454. # if event.key == 'S':
  3455. # self.on_filerunscript()
  3456. #
  3457. # # Toggle Workspace
  3458. # if event.key == 'W':
  3459. # self.on_workspace_menu()
  3460. #
  3461. # # Skew on X axis
  3462. # if event.key == 'X':
  3463. # self.on_skewx()
  3464. #
  3465. # # Skew on Y axis
  3466. # if event.key == 'Y':
  3467. # self.on_skewy()
  3468. #
  3469. # else:
  3470. # if event.key == 'F1':
  3471. # webbrowser.open(self.manual_url)
  3472. # return
  3473. #
  3474. # if event.key == 'F2':
  3475. # webbrowser.open(self.video_url)
  3476. # return
  3477. #
  3478. # if event.key == self.defaults['zoom_out_key']: # '-'
  3479. # self.plotcanvas.zoom(1 / self.defaults['zoom_ratio'], self.mouse)
  3480. # return
  3481. #
  3482. # if event.key == self.defaults['zoom_in_key']: # '='
  3483. # self.plotcanvas.zoom(self.defaults['zoom_ratio'], self.mouse)
  3484. # return
  3485. #
  3486. # if event.key == 'Delete':
  3487. # self.on_delete()
  3488. # return
  3489. #
  3490. # if event.key == 'Space':
  3491. # if self.collection.get_active() is not None:
  3492. # self.collection.get_active().ui.plot_cb.toggle()
  3493. # self.delete_selection_shape()
  3494. #
  3495. # if event.key == '1':
  3496. # self.on_select_tab('project')
  3497. #
  3498. # if event.key == '2':
  3499. # self.on_select_tab('selected')
  3500. #
  3501. # if event.key == '3':
  3502. # self.on_select_tab('tool')
  3503. #
  3504. # if event.key == 'E':
  3505. # self.object2editor()
  3506. #
  3507. # if event.key == self.defaults['grid_toggle_key']: # G
  3508. # self.ui.grid_snap_btn.trigger()
  3509. #
  3510. # if event.key == 'J':
  3511. # self.on_jump_to()
  3512. #
  3513. # if event.key == 'L':
  3514. # self.new_excellon_object()
  3515. #
  3516. # if event.key == 'M':
  3517. # self.move_tool.toggle()
  3518. # return
  3519. #
  3520. # if event.key == 'N':
  3521. # self.on_new_geometry()
  3522. #
  3523. # if event.key == 'O':
  3524. # self.on_set_origin()
  3525. #
  3526. # if event.key == 'P':
  3527. # self.properties_tool.run()
  3528. #
  3529. # if event.key == 'Q':
  3530. # self.on_toggle_units_click()
  3531. #
  3532. # if event.key == 'R':
  3533. # self.on_rotate(silent=True, preset=90)
  3534. #
  3535. # if event.key == 'S':
  3536. # self.on_toggle_shell()
  3537. #
  3538. # if event.key == 'V':
  3539. # self.on_zoom_fit(None)
  3540. #
  3541. # if event.key == 'X':
  3542. # self.on_flipx()
  3543. #
  3544. # if event.key == 'Y':
  3545. # self.on_flipy()
  3546. #
  3547. # if event.key == '`':
  3548. # self.on_shortcut_list()
  3549. #
  3550. # def on_key_release_over_plot(self, event):
  3551. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  3552. #
  3553. # if modifiers == QtCore.Qt.ControlModifier:
  3554. # return
  3555. # elif modifiers == QtCore.Qt.AltModifier:
  3556. # # place holder for further shortcut key
  3557. # return
  3558. # elif modifiers == QtCore.Qt.ShiftModifier:
  3559. # # place holder for further shortcut key
  3560. # return
  3561. # else:
  3562. # return
  3563. def on_shortcut_list(self):
  3564. self.report_usage("on_shortcut_list()")
  3565. # add the tab if it was closed
  3566. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  3567. # delete the absolute and relative position and messages in the infobar
  3568. self.ui.position_label.setText("")
  3569. self.ui.rel_position_label.setText("")
  3570. # Switch plot_area to preferences page
  3571. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  3572. self.ui.show()
  3573. def on_select_tab(self, name):
  3574. if name == 'project':
  3575. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3576. elif name == 'selected':
  3577. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3578. elif name == 'tool':
  3579. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  3580. # if the splitter us hidden, display it
  3581. if self.ui.splitter.sizes()[0] == 0:
  3582. self.ui.splitter.setSizes([1, 1])
  3583. def on_copy_name(self):
  3584. self.report_usage("on_copy_name()")
  3585. obj = self.collection.get_active()
  3586. try:
  3587. name = obj.options["name"]
  3588. except AttributeError:
  3589. log.debug("on_copy_name() --> No object selected to copy it's name")
  3590. self.inform.emit("[WARNING_NOTCL]No object selected to copy it's name")
  3591. return
  3592. self.clipboard.setText(name)
  3593. self.inform.emit("Name copied on clipboard ...")
  3594. def on_mouse_click_over_plot(self, event):
  3595. """
  3596. Callback for the mouse click event over the plot. This event is generated
  3597. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3598. For details, see: http://matplotlib.org/users/event_handling.html
  3599. Default actions are:
  3600. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  3601. :param event: Contains information about the event, like which button
  3602. was clicked, the pixel coordinates and the axes coordinates.
  3603. :return: None
  3604. """
  3605. self.pos = []
  3606. # So it can receive key presses
  3607. self.plotcanvas.vispy_canvas.native.setFocus()
  3608. # Set the mouse button for panning
  3609. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  3610. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3611. if self.grid_status() == True:
  3612. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  3613. self.app_cursor.enabled = True
  3614. else:
  3615. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  3616. self.app_cursor.enabled = False
  3617. try:
  3618. # App.log.debug('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  3619. # event.button, event.pos[0], event.pos[1], self.pos[0], self.pos[1]))
  3620. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3621. if event.button == 1:
  3622. # Reset here the relative coordinates so there is a new reference on the click position
  3623. if self.rel_point1 is None:
  3624. self.rel_point1 = self.pos
  3625. else:
  3626. self.rel_point2 = copy(self.rel_point1)
  3627. self.rel_point1 = self.pos
  3628. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3629. if modifiers == QtCore.Qt.ShiftModifier:
  3630. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3631. return
  3632. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  3633. # and if it's not selected then it will be selected
  3634. if modifiers == QtCore.Qt.ControlModifier:
  3635. # If there is no active command (self.command_active is None) then we check if we clicked on
  3636. # a object by checking the bounding limits against mouse click position
  3637. if self.command_active is None:
  3638. self.select_objects(key='CTRL')
  3639. else:
  3640. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  3641. # checking the bounding limits against mouse click position
  3642. if self.command_active is None:
  3643. self.select_objects()
  3644. self.on_mouse_move_over_plot(event, origin_click=True)
  3645. except Exception as e:
  3646. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  3647. def on_double_click_over_plot(self, event):
  3648. # make double click work only for the LMB
  3649. if event.button == 1:
  3650. if self.collection.get_selected():
  3651. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3652. # delete the selection shape(S) as it may be in the way
  3653. self.delete_selection_shape()
  3654. def on_mouse_move_over_plot(self, event, origin_click=None):
  3655. """
  3656. Callback for the mouse motion event over the plot. This event is generated
  3657. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3658. For details, see: http://matplotlib.org/users/event_handling.html
  3659. :param event: Contains information about the event.
  3660. :param origin_click
  3661. :return: None
  3662. """
  3663. # So it can receive key presses
  3664. self.plotcanvas.vispy_canvas.native.setFocus()
  3665. self.pos_jump = event.pos
  3666. if origin_click is True:
  3667. pass
  3668. else:
  3669. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3670. if event.button == 2:
  3671. self.panning_action = True
  3672. return
  3673. else:
  3674. self.panning_action = False
  3675. if self.rel_point1 is not None:
  3676. try: # May fail in case mouse not within axes
  3677. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3678. if self.grid_status():
  3679. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3680. self.app_cursor.enabled = True
  3681. # Update cursor
  3682. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  3683. else:
  3684. pos = (pos_canvas[0], pos_canvas[1])
  3685. self.app_cursor.enabled = False
  3686. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3687. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  3688. dx = pos[0] - self.rel_point1[0]
  3689. dy = pos[1] - self.rel_point1[1]
  3690. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3691. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3692. self.mouse = [pos[0], pos[1]]
  3693. # if the mouse is moved and the LMB is clicked then the action is a selection
  3694. if event.is_dragging == 1 and event.button == 1:
  3695. self.delete_selection_shape()
  3696. if dx < 0:
  3697. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  3698. face_color=self.defaults['global_alt_sel_fill'])
  3699. self.selection_type = False
  3700. else:
  3701. self.draw_moving_selection_shape(self.pos, pos)
  3702. self.selection_type = True
  3703. # delete the status message on mouse move
  3704. # self.inform.emit("")
  3705. except:
  3706. self.ui.position_label.setText("")
  3707. self.ui.rel_position_label.setText("")
  3708. self.mouse = None
  3709. def on_mouse_click_release_over_plot(self, event):
  3710. """
  3711. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  3712. and has been registered in ''self.__init__()''.
  3713. :param event: contains information about the event.
  3714. :return:
  3715. """
  3716. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3717. if self.grid_status():
  3718. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3719. else:
  3720. pos = (pos_canvas[0], pos_canvas[1])
  3721. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3722. # canvas menu
  3723. try:
  3724. if event.button == 2: # right click
  3725. if self.panning_action is True:
  3726. self.panning_action = False
  3727. else:
  3728. self.cursor = QtGui.QCursor()
  3729. self.ui.popMenu.popup(self.cursor.pos())
  3730. except Exception as e:
  3731. log.warning("Error: %s" % str(e))
  3732. return
  3733. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3734. # selection and then select a type of selection ("enclosing" or "touching")
  3735. try:
  3736. if event.button == 1: # left click
  3737. if self.selection_type is not None:
  3738. self.selection_area_handler(self.pos, pos, self.selection_type)
  3739. self.selection_type = None
  3740. except Exception as e:
  3741. log.warning("Error: %s" % str(e))
  3742. return
  3743. def selection_area_handler(self, start_pos, end_pos, sel_type):
  3744. """
  3745. :param start_pos: mouse position when the selection LMB click was done
  3746. :param end_pos: mouse position when the left mouse button is released
  3747. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3748. :return:
  3749. """
  3750. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3751. self.delete_selection_shape()
  3752. for obj in self.collection.get_list():
  3753. try:
  3754. # select the object(s) only if it is enabled (plotted)
  3755. if obj.options['plot']:
  3756. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']), (obj.options['xmax'], obj.options['ymin']),
  3757. (obj.options['xmax'], obj.options['ymax']), (obj.options['xmin'], obj.options['ymax'])])
  3758. if sel_type is True:
  3759. if poly_obj.within(poly_selection):
  3760. # create the selection box around the selected object
  3761. self.draw_selection_shape(obj)
  3762. self.collection.set_active(obj.options['name'])
  3763. else:
  3764. if poly_selection.intersects(poly_obj):
  3765. # create the selection box around the selected object
  3766. self.draw_selection_shape(obj)
  3767. self.collection.set_active(obj.options['name'])
  3768. except:
  3769. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  3770. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  3771. # In this case poly_obj creation (see above) will fail
  3772. pass
  3773. def select_objects(self, key=None):
  3774. # list where we store the overlapped objects under our mouse left click position
  3775. objects_under_the_click_list = []
  3776. # Populate the list with the overlapped objects on the click position
  3777. curr_x, curr_y = self.pos
  3778. for obj in self.all_objects_list:
  3779. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  3780. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  3781. if obj.options['name'] not in objects_under_the_click_list:
  3782. if obj.options['plot']:
  3783. # add objects to the objects_under_the_click list only if the object is plotted
  3784. # (active and not disabled)
  3785. objects_under_the_click_list.append(obj.options['name'])
  3786. try:
  3787. # If there is no element in the overlapped objects list then make everyone inactive
  3788. # because we selected "nothing"
  3789. if not objects_under_the_click_list:
  3790. self.collection.set_all_inactive()
  3791. # delete the possible selection box around a possible selected object
  3792. self.delete_selection_shape()
  3793. # and as a convenience move the focus to the Project tab because Selected tab is now empty
  3794. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3795. # delete any text in the status bar, implicitly the last object name that was selected
  3796. self.inform.emit("")
  3797. else:
  3798. # case when there is only an object under the click and we toggle it
  3799. if len(objects_under_the_click_list) == 1:
  3800. if self.collection.get_active() is None :
  3801. self.collection.set_active(objects_under_the_click_list[0])
  3802. # create the selection box around the selected object
  3803. curr_sel_obj = self.collection.get_active()
  3804. self.draw_selection_shape(curr_sel_obj)
  3805. # self.inform.emit('[selected] %s: %s selected' %
  3806. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3807. if curr_sel_obj.kind == 'gerber':
  3808. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3809. ('green', str(curr_sel_obj.options['name'])))
  3810. elif curr_sel_obj.kind == 'excellon':
  3811. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3812. ('brown', str(curr_sel_obj.options['name'])))
  3813. elif curr_sel_obj.kind == 'cncjob':
  3814. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3815. ('blue', str(curr_sel_obj.options['name'])))
  3816. elif curr_sel_obj.kind == 'geometry':
  3817. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3818. ('red', str(curr_sel_obj.options['name'])))
  3819. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  3820. self.collection.set_all_inactive()
  3821. self.delete_selection_shape()
  3822. self.collection.set_active(objects_under_the_click_list[0])
  3823. # create the selection box around the selected object
  3824. curr_sel_obj = self.collection.get_active()
  3825. self.draw_selection_shape(curr_sel_obj)
  3826. # self.inform.emit('[selected] %s: %s selected' %
  3827. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3828. if curr_sel_obj.kind == 'gerber':
  3829. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3830. ('green', str(curr_sel_obj.options['name'])))
  3831. elif curr_sel_obj.kind == 'excellon':
  3832. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3833. ('brown', str(curr_sel_obj.options['name'])))
  3834. elif curr_sel_obj.kind == 'cncjob':
  3835. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3836. ('blue', str(curr_sel_obj.options['name'])))
  3837. elif curr_sel_obj.kind == 'geometry':
  3838. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3839. ('red', str(curr_sel_obj.options['name'])))
  3840. else:
  3841. self.collection.set_all_inactive()
  3842. self.delete_selection_shape()
  3843. self.inform.emit("")
  3844. else:
  3845. # If there is no selected object
  3846. # make active the first element of the overlapped objects list
  3847. if self.collection.get_active() is None:
  3848. self.collection.set_active(objects_under_the_click_list[0])
  3849. name_sel_obj = self.collection.get_active().options['name']
  3850. # In case that there is a selected object but it is not in the overlapped object list
  3851. # make that object inactive and activate the first element in the overlapped object list
  3852. if name_sel_obj not in objects_under_the_click_list:
  3853. self.collection.set_inactive(name_sel_obj)
  3854. name_sel_obj = objects_under_the_click_list[0]
  3855. self.collection.set_active(name_sel_obj)
  3856. else:
  3857. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  3858. self.collection.set_all_inactive()
  3859. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  3860. len(objects_under_the_click_list)])
  3861. curr_sel_obj = self.collection.get_active()
  3862. # delete the possible selection box around a possible selected object
  3863. self.delete_selection_shape()
  3864. # create the selection box around the selected object
  3865. self.draw_selection_shape(curr_sel_obj)
  3866. # self.inform.emit('[selected] %s: %s selected' %
  3867. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3868. if curr_sel_obj.kind == 'gerber':
  3869. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3870. ('green', str(curr_sel_obj.options['name'])))
  3871. elif curr_sel_obj.kind == 'excellon':
  3872. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3873. ('brown', str(curr_sel_obj.options['name'])))
  3874. elif curr_sel_obj.kind == 'cncjob':
  3875. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3876. ('blue', str(curr_sel_obj.options['name'])))
  3877. elif curr_sel_obj.kind == 'geometry':
  3878. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3879. ('red', str(curr_sel_obj.options['name'])))
  3880. # for obj in self.collection.get_list():
  3881. # obj.plot()
  3882. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  3883. # TODO: on selected objects change the object colors and do not draw the selection box
  3884. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  3885. except Exception as e:
  3886. log.error("[ERROR] Something went bad. %s" % str(e))
  3887. return
  3888. def delete_selection_shape(self):
  3889. self.move_tool.sel_shapes.clear()
  3890. self.move_tool.sel_shapes.redraw()
  3891. def draw_selection_shape(self, sel_obj):
  3892. """
  3893. :param sel_obj: the object for which the selection shape must be drawn
  3894. :return:
  3895. """
  3896. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  3897. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  3898. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  3899. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  3900. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3901. #blue_t = Color('blue')
  3902. blue_t = Color(self.defaults['global_sel_fill'])
  3903. blue_t.alpha = 0.3
  3904. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=self.defaults['global_sel_line'],
  3905. face_color=blue_t, update=True, layer=0, tolerance=None))
  3906. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  3907. """
  3908. :param old_coords: old coordinates
  3909. :param coords: new coordinates
  3910. :return:
  3911. """
  3912. if 'color' in kwargs:
  3913. color = kwargs['color']
  3914. else:
  3915. color = self.defaults['global_sel_line']
  3916. if 'face_color' in kwargs:
  3917. face_color = kwargs['face_color']
  3918. else:
  3919. face_color = self.defaults['global_sel_fill']
  3920. x0, y0 = old_coords
  3921. x1, y1 = coords
  3922. pt1 = (x0, y0)
  3923. pt2 = (x1, y0)
  3924. pt3 = (x1, y1)
  3925. pt4 = (x0, y1)
  3926. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3927. color_t = Color(face_color)
  3928. color_t.alpha = 0.3
  3929. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  3930. layer=0, tolerance=None)
  3931. def on_file_new_click(self):
  3932. if self.collection.get_list():
  3933. msgbox = QtWidgets.QMessageBox()
  3934. # msgbox.setText("<B>Save changes ...</B>")
  3935. msgbox.setText("There are files/objects opened in FlatCAM.\n"
  3936. "Creating a New project will delete them.\n"
  3937. "Do you want to Save the project?")
  3938. msgbox.setWindowTitle("Save changes")
  3939. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3940. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Yes |
  3941. QtWidgets.QMessageBox.No)
  3942. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3943. response = msgbox.exec_()
  3944. if response == QtWidgets.QMessageBox.Yes:
  3945. self.on_file_saveprojectas()
  3946. elif response == QtWidgets.QMessageBox.Cancel:
  3947. return
  3948. self.on_file_new()
  3949. else:
  3950. self.on_file_new()
  3951. self.inform.emit("[success] New Project created...")
  3952. def on_file_new(self):
  3953. """
  3954. Callback for menu item File->New. Returns the application to its
  3955. startup state. This method is thread-safe.
  3956. :return: None
  3957. """
  3958. self.report_usage("on_file_new")
  3959. # Remove everything from memory
  3960. App.log.debug("on_file_new()")
  3961. # Clear pool
  3962. self.clear_pool()
  3963. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  3964. self.init_tcl()
  3965. self.delete_selection_shape()
  3966. self.collection.delete_all()
  3967. self.setup_component_editor()
  3968. # Clear project filename
  3969. self.project_filename = None
  3970. # Load the application defaults
  3971. self.load_defaults(filename='current_defaults')
  3972. # Re-fresh project options
  3973. self.on_options_app2project()
  3974. # Init Tools
  3975. self.init_tools()
  3976. # take the focus of the Notebook on Project Tab.
  3977. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3978. def obj_properties(self):
  3979. self.report_usage("obj_properties()")
  3980. self.properties_tool.run()
  3981. def obj_move(self):
  3982. self.report_usage("obj_move()")
  3983. self.move_tool.run()
  3984. def on_fileopengerber(self):
  3985. """
  3986. File menu callback for opening a Gerber.
  3987. :return: None
  3988. """
  3989. self.report_usage("on_fileopengerber")
  3990. App.log.debug("on_fileopengerber()")
  3991. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3992. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3993. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3994. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3995. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3996. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3997. "Allegro Files (*.art);;" \
  3998. "Mentor Files (*.pho *.gdo);;" \
  3999. "All Files (*.*)"
  4000. try:
  4001. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber",
  4002. directory=self.get_last_folder(), filter=_filter_)
  4003. except TypeError:
  4004. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber", filter=_filter_)
  4005. filenames = [str(filename) for filename in filenames]
  4006. if len(filenames) == 0:
  4007. self.inform.emit("[WARNING_NOTCL]Open Gerber cancelled.")
  4008. else:
  4009. for filename in filenames:
  4010. if filename != '':
  4011. self.worker_task.emit({'fcn': self.open_gerber,
  4012. 'params': [filename]})
  4013. def on_fileopengerber_follow(self):
  4014. """
  4015. File menu callback for opening a Gerber.
  4016. :return: None
  4017. """
  4018. self.report_usage("on_fileopengerber_follow")
  4019. App.log.debug("on_fileopengerber_follow()")
  4020. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  4021. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  4022. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  4023. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  4024. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  4025. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  4026. "Allegro Files (*.art);;" \
  4027. "Mentor Files (*.pho *.gdo);;" \
  4028. "All Files (*.*)"
  4029. try:
  4030. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow",
  4031. directory=self.get_last_folder(), filter=_filter_)
  4032. except TypeError:
  4033. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow", filter=_filter_)
  4034. # The Qt methods above will return a QString which can cause problems later.
  4035. # So far json.dump() will fail to serialize it.
  4036. # TODO: Improve the serialization methods and remove this fix.
  4037. filename = str(filename)
  4038. follow = True
  4039. if filename == "":
  4040. self.inform.emit("[WARNING_NOTCL]Open Gerber-Follow cancelled.")
  4041. else:
  4042. self.worker_task.emit({'fcn': self.open_gerber,
  4043. 'params': [filename, follow]})
  4044. def on_fileopenexcellon(self):
  4045. """
  4046. File menu callback for opening an Excellon file.
  4047. :return: None
  4048. """
  4049. self.report_usage("on_fileopenexcellon")
  4050. App.log.debug("on_fileopenexcellon()")
  4051. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  4052. "All Files (*.*)"
  4053. try:
  4054. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon",
  4055. directory=self.get_last_folder(), filter=_filter_)
  4056. except TypeError:
  4057. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon", filter=_filter_)
  4058. filenames = [str(filename) for filename in filenames]
  4059. if len(filenames) == 0:
  4060. self.inform.emit("[WARNING_NOTCL]Open Excellon cancelled.")
  4061. else:
  4062. for filename in filenames:
  4063. if filename != '':
  4064. self.worker_task.emit({'fcn': self.open_excellon,
  4065. 'params': [filename]})
  4066. def on_fileopengcode(self):
  4067. """
  4068. File menu call back for opening gcode.
  4069. :return: None
  4070. """
  4071. self.report_usage("on_fileopengcode")
  4072. App.log.debug("on_fileopengcode()")
  4073. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  4074. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  4075. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  4076. "All Files (*.*)"
  4077. try:
  4078. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code",
  4079. directory=self.get_last_folder(), filter=_filter_)
  4080. except TypeError:
  4081. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code", filter=_filter_)
  4082. filenames = [str(filename) for filename in filenames]
  4083. if len(filenames) == 0:
  4084. self.inform.emit("[WARNING_NOTCL]Open G-Code cancelled.")
  4085. else:
  4086. for filename in filenames:
  4087. if filename != '':
  4088. self.worker_task.emit({'fcn': self.open_gcode,
  4089. 'params': [filename]})
  4090. def on_file_openproject(self):
  4091. """
  4092. File menu callback for opening a project.
  4093. :return: None
  4094. """
  4095. self.report_usage("on_file_openproject")
  4096. App.log.debug("on_file_openproject()")
  4097. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  4098. try:
  4099. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project",
  4100. directory=self.get_last_folder(), filter=_filter_)
  4101. except TypeError:
  4102. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project", filter = _filter_)
  4103. # The Qt methods above will return a QString which can cause problems later.
  4104. # So far json.dump() will fail to serialize it.
  4105. # TODO: Improve the serialization methods and remove this fix.
  4106. filename = str(filename)
  4107. if filename == "":
  4108. self.inform.emit("[WARNING_NOTCL]Open Project cancelled.")
  4109. else:
  4110. # self.worker_task.emit({'fcn': self.open_project,
  4111. # 'params': [filename]})
  4112. # The above was failing because open_project() is not
  4113. # thread safe. The new_project()
  4114. self.open_project(filename)
  4115. def on_file_exportsvg(self):
  4116. """
  4117. Callback for menu item File->Export SVG.
  4118. :return: None
  4119. """
  4120. self.report_usage("on_file_exportsvg")
  4121. App.log.debug("on_file_exportsvg()")
  4122. obj = self.collection.get_active()
  4123. if obj is None:
  4124. self.inform.emit("WARNING: No object selected.")
  4125. msg = "Please Select a Geometry object to export"
  4126. msgbox = QtWidgets.QMessageBox()
  4127. msgbox.setInformativeText(msg)
  4128. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4129. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4130. msgbox.exec_()
  4131. return
  4132. # Check for more compatible types and add as required
  4133. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  4134. and not isinstance(obj, FlatCAMExcellon)):
  4135. msg = "[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used."
  4136. msgbox = QtWidgets.QMessageBox()
  4137. msgbox.setInformativeText(msg)
  4138. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4139. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4140. msgbox.exec_()
  4141. return
  4142. name = self.collection.get_active().options["name"]
  4143. filter = "SVG File (*.svg);;All Files (*.*)"
  4144. try:
  4145. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4146. caption="Export SVG",
  4147. directory=self.get_last_save_folder() + '/' + str(name),
  4148. filter=filter)
  4149. except TypeError:
  4150. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG", filter=filter)
  4151. filename = str(filename)
  4152. if filename == "":
  4153. self.inform.emit("[WARNING_NOTCL]Export SVG cancelled.")
  4154. return
  4155. else:
  4156. self.export_svg(name, filename)
  4157. self.file_saved.emit("SVG", filename)
  4158. def on_file_exportpng(self):
  4159. self.report_usage("on_file_exportpng")
  4160. App.log.debug("on_file_exportpng()")
  4161. image = _screenshot()
  4162. data = np.asarray(image)
  4163. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  4164. self.inform.emit('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4')
  4165. return
  4166. filter_ = "PNG File (*.png);;All Files (*.*)"
  4167. try:
  4168. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4169. caption="Export PNG Image",
  4170. directory=self.get_last_save_folder() + '/png_' + str(self.date).replace('-', ''),
  4171. filter=filter_)
  4172. except TypeError:
  4173. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image", filter=filter_)
  4174. filename = str(filename)
  4175. if filename == "":
  4176. self.inform.emit("Export PNG cancelled.")
  4177. return
  4178. else:
  4179. write_png(filename, data)
  4180. self.file_saved.emit("png", filename)
  4181. def on_file_exportexcellon(self, altium_format=None):
  4182. """
  4183. Callback for menu item File->Export SVG.
  4184. :return: None
  4185. """
  4186. self.report_usage("on_file_exportexcellon")
  4187. App.log.debug("on_file_exportexcellon()")
  4188. obj = self.collection.get_active()
  4189. if obj is None:
  4190. self.inform.emit("[WARNING_NOTCL] No object selected.")
  4191. msg = "Please Select an Excellon object to export"
  4192. msgbox = QtWidgets.QMessageBox()
  4193. msgbox.setInformativeText(msg)
  4194. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4195. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4196. msgbox.exec_()
  4197. return
  4198. # Check for more compatible types and add as required
  4199. if not isinstance(obj, FlatCAMExcellon):
  4200. msg = "[WARNING_NOTCL] Only Excellon objects can be used."
  4201. msgbox = QtWidgets.QMessageBox()
  4202. msgbox.setInformativeText(msg)
  4203. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4204. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4205. msgbox.exec_()
  4206. return
  4207. name = self.collection.get_active().options["name"]
  4208. filter = "Excellon File (*.drl);;Excellon File (*.txt);;All Files (*.*)"
  4209. try:
  4210. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4211. caption="Export Excellon",
  4212. directory=self.get_last_save_folder() + '/' + name,
  4213. filter=filter)
  4214. except TypeError:
  4215. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon", filter=filter)
  4216. filename = str(filename)
  4217. if filename == "":
  4218. self.inform.emit("[WARNING_NOTCL]Export Excellon cancelled.")
  4219. return
  4220. else:
  4221. if altium_format is None:
  4222. self.export_excellon(name, filename)
  4223. self.file_saved.emit("Excellon", filename)
  4224. else:
  4225. self.export_excellon(name, filename, altium_format=True)
  4226. self.file_saved.emit("Excellon", filename)
  4227. def on_file_exportdxf(self):
  4228. """
  4229. Callback for menu item File->Export DXF.
  4230. :return: None
  4231. """
  4232. self.report_usage("on_file_exportdxf")
  4233. App.log.debug("on_file_exportdxf()")
  4234. obj = self.collection.get_active()
  4235. if obj is None:
  4236. self.inform.emit("W[WARNING_NOTCL] No object selected.")
  4237. msg = "Please Select a Geometry object to export"
  4238. msgbox = QtWidgets.QMessageBox()
  4239. msgbox.setInformativeText(msg)
  4240. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4241. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4242. msgbox.exec_()
  4243. return
  4244. # Check for more compatible types and add as required
  4245. if not isinstance(obj, FlatCAMGeometry):
  4246. msg = "[ERROR_NOTCL] Only Geometry objects can be used."
  4247. msgbox = QtWidgets.QMessageBox()
  4248. msgbox.setInformativeText(msg)
  4249. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4250. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4251. msgbox.exec_()
  4252. return
  4253. name = self.collection.get_active().options["name"]
  4254. filter = "DXF File (*.DXF);;All Files (*.*)"
  4255. try:
  4256. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4257. caption="Export DXF",
  4258. directory=self.get_last_save_folder() + '/' + name,
  4259. filter=filter)
  4260. except TypeError:
  4261. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF", filter=filter)
  4262. filename = str(filename)
  4263. if filename == "":
  4264. self.inform.emit("[WARNING_NOTCL]Export DXF cancelled.")
  4265. return
  4266. else:
  4267. self.export_dxf(name, filename)
  4268. self.file_saved.emit("DXF", filename)
  4269. def on_file_importsvg(self, type_of_obj):
  4270. """
  4271. Callback for menu item File->Import SVG.
  4272. :param type_of_obj: to import the SVG as Geometry or as Gerber
  4273. :type type_of_obj: str
  4274. :return: None
  4275. """
  4276. self.report_usage("on_file_importsvg")
  4277. App.log.debug("on_file_importsvg()")
  4278. filter = "SVG File (*.svg);;All Files (*.*)"
  4279. try:
  4280. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG",
  4281. directory=self.get_last_folder(), filter=filter)
  4282. except TypeError:
  4283. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG", filter=filter)
  4284. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4285. type_of_obj = "geometry"
  4286. filenames = [str(filename) for filename in filenames]
  4287. if len(filenames) == 0:
  4288. self.inform.emit("[WARNING_NOTCL]Open SVG cancelled.")
  4289. else:
  4290. for filename in filenames:
  4291. if filename != '':
  4292. self.worker_task.emit({'fcn': self.import_svg,
  4293. 'params': [filename, type_of_obj]})
  4294. def on_file_importdxf(self, type_of_obj):
  4295. """
  4296. Callback for menu item File->Import DXF.
  4297. :param type_of_obj: to import the DXF as Geometry or as Gerber
  4298. :type type_of_obj: str
  4299. :return: None
  4300. """
  4301. self.report_usage("on_file_importdxf")
  4302. App.log.debug("on_file_importdxf()")
  4303. filter = "DXF File (*.DXF);;All Files (*.*)"
  4304. try:
  4305. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF",
  4306. directory=self.get_last_folder(), filter=filter)
  4307. except TypeError:
  4308. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF", filter=filter)
  4309. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4310. type_of_obj = "geometry"
  4311. filenames = [str(filename) for filename in filenames]
  4312. if len(filenames) == 0:
  4313. self.inform.emit("[WARNING_NOTCL]Open DXF cancelled.")
  4314. else:
  4315. for filename in filenames:
  4316. if filename != '':
  4317. self.worker_task.emit({'fcn': self.import_dxf,
  4318. 'params': [filename, type_of_obj]})
  4319. def on_filerunscript(self):
  4320. """
  4321. File menu callback for loading and running a TCL script.
  4322. :return: None
  4323. """
  4324. self.report_usage("on_filerunscript")
  4325. App.log.debug("on_file_runscript()")
  4326. _filter_ = "TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  4327. try:
  4328. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script",
  4329. directory=self.get_last_folder(), filter=_filter_)
  4330. except TypeError:
  4331. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script", filter=_filter_)
  4332. # The Qt methods above will return a QString which can cause problems later.
  4333. # So far json.dump() will fail to serialize it.
  4334. # TODO: Improve the serialization methods and remove this fix.
  4335. filename = str(filename)
  4336. if filename == "":
  4337. self.inform.emit("[WARNING_NOTCL]Open TCL script cancelled.")
  4338. else:
  4339. try:
  4340. with open(filename, "r") as tcl_script:
  4341. cmd_line_shellfile_content = tcl_script.read()
  4342. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  4343. except Exception as ext:
  4344. print("ERROR: ", ext)
  4345. sys.exit(2)
  4346. def on_file_saveproject(self):
  4347. """
  4348. Callback for menu item File->Save Project. Saves the project to
  4349. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  4350. if set to None. The project is saved by calling ``self.save_project()``.
  4351. :return: None
  4352. """
  4353. self.report_usage("on_file_saveproject")
  4354. if self.project_filename is None:
  4355. self.on_file_saveprojectas()
  4356. else:
  4357. self.worker_task.emit({'fcn': self.save_project,
  4358. 'params': [self.project_filename]})
  4359. # self.save_project(self.project_filename)
  4360. self.file_opened.emit("project", self.project_filename)
  4361. self.file_saved.emit("project", self.project_filename)
  4362. def on_file_saveprojectas(self, make_copy=False, thread=True):
  4363. """
  4364. Callback for menu item File->Save Project As... Opens a file
  4365. chooser and saves the project to the given file via
  4366. ``self.save_project()``.
  4367. :return: None
  4368. """
  4369. self.report_usage("on_file_saveprojectas")
  4370. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  4371. try:
  4372. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4373. caption="Save Project As ...",
  4374. directory=self.get_last_save_folder() + '/Project_' + self.date.replace('-', ''),
  4375. filter=filter_)
  4376. except TypeError:
  4377. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...", filter=filter_)
  4378. filename = str(filename)
  4379. if filename == '':
  4380. self.inform.emit("[WARNING_NOTCL]Save Project cancelled.")
  4381. return
  4382. try:
  4383. f = open(filename, 'r')
  4384. f.close()
  4385. exists = True
  4386. except IOError:
  4387. exists = False
  4388. msg = "File exists. Overwrite?"
  4389. if exists:
  4390. msgbox = QtWidgets.QMessageBox()
  4391. msgbox.setInformativeText(msg)
  4392. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel |QtWidgets.QMessageBox.Ok)
  4393. msgbox.setDefaultButton(QtWidgets.QMessageBox.Cancel)
  4394. result = msgbox.exec_()
  4395. if result ==QtWidgets.QMessageBox.Cancel:
  4396. return
  4397. if thread is True:
  4398. self.worker_task.emit({'fcn': self.save_project,
  4399. 'params': [filename]})
  4400. else:
  4401. self.save_project(filename)
  4402. # self.save_project(filename)
  4403. self.file_opened.emit("project", filename)
  4404. self.file_saved.emit("project", filename)
  4405. if not make_copy:
  4406. self.project_filename = filename
  4407. def export_svg(self, obj_name, filename, scale_factor=0.00):
  4408. """
  4409. Exports a Geometry Object to an SVG file.
  4410. :param filename: Path to the SVG file to save to.
  4411. :return:
  4412. """
  4413. self.report_usage("export_svg()")
  4414. if filename is None:
  4415. filename = self.defaults["global_last_save_folder"]
  4416. self.log.debug("export_svg()")
  4417. try:
  4418. obj = self.collection.get_by_name(str(obj_name))
  4419. except:
  4420. # TODO: The return behavior has not been established... should raise exception?
  4421. return "Could not retrieve object: %s" % obj_name
  4422. with self.proc_container.new("Exporting SVG") as proc:
  4423. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4424. # Determine bounding area for svg export
  4425. bounds = obj.bounds()
  4426. size = obj.size()
  4427. # Convert everything to strings for use in the xml doc
  4428. svgwidth = str(size[0])
  4429. svgheight = str(size[1])
  4430. minx = str(bounds[0])
  4431. miny = str(bounds[1] - size[1])
  4432. uom = obj.units.lower()
  4433. # Add a SVG Header and footer to the svg output from shapely
  4434. # The transform flips the Y Axis so that everything renders
  4435. # properly within svg apps such as inkscape
  4436. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4437. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4438. svg_header += 'width="' + svgwidth + uom + '" '
  4439. svg_header += 'height="' + svgheight + uom + '" '
  4440. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  4441. svg_header += '<g transform="scale(1,-1)">'
  4442. svg_footer = '</g> </svg>'
  4443. svg_elem = svg_header + exported_svg + svg_footer
  4444. # Parse the xml through a xml parser just to add line feeds
  4445. # and to make it look more pretty for the output
  4446. svgcode = parse_xml_string(svg_elem)
  4447. with open(filename, 'w') as fp:
  4448. fp.write(svgcode.toprettyxml())
  4449. self.file_saved.emit("SVG", filename)
  4450. self.inform.emit("[success] SVG file exported to " + filename)
  4451. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  4452. """
  4453. Exports a Geometry Object to an SVG file in negative.
  4454. :param filename: Path to the SVG file to save to.
  4455. :param: use_thread: If True use threads
  4456. :type: Bool
  4457. :return:
  4458. """
  4459. self.report_usage("export_negative()")
  4460. if filename is None:
  4461. filename = self.defaults["global_last_save_folder"]
  4462. self.log.debug("export_svg() negative")
  4463. try:
  4464. obj = self.collection.get_by_name(str(obj_name))
  4465. except:
  4466. # TODO: The return behavior has not been established... should raise exception?
  4467. return "Could not retrieve object: %s" % obj_name
  4468. try:
  4469. box = self.collection.get_by_name(str(box_name))
  4470. except:
  4471. # TODO: The return behavior has not been established... should raise exception?
  4472. return "Could not retrieve object: %s" % box_name
  4473. if box is None:
  4474. self.inform.emit("[WARNING_NOTCL]No object Box. Using instead %s" % obj)
  4475. box = obj
  4476. def make_negative_film():
  4477. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4478. self.progress.emit(40)
  4479. # Determine bounding area for svg export
  4480. bounds = box.bounds()
  4481. size = box.size()
  4482. uom = obj.units.lower()
  4483. # Convert everything to strings for use in the xml doc
  4484. svgwidth = str(size[0] + (2 * boundary))
  4485. svgheight = str(size[1] + (2 * boundary))
  4486. minx = str(bounds[0] - boundary)
  4487. miny = str(bounds[1] + boundary + size[1])
  4488. miny_rect = str(bounds[1] - boundary)
  4489. # Add a SVG Header and footer to the svg output from shapely
  4490. # The transform flips the Y Axis so that everything renders
  4491. # properly within svg apps such as inkscape
  4492. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4493. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4494. svg_header += 'width="' + svgwidth + uom + '" '
  4495. svg_header += 'height="' + svgheight + uom + '" '
  4496. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4497. svg_header += '>'
  4498. svg_header += '<g transform="scale(1,-1)">'
  4499. svg_footer = '</g> </svg>'
  4500. self.progress.emit(60)
  4501. # Change the attributes of the exported SVG
  4502. # We don't need stroke-width - wrong, we do when we have lines with certain width
  4503. # We set opacity to maximum
  4504. # We set the color to WHITE
  4505. root = ET.fromstring(exported_svg)
  4506. for child in root:
  4507. child.set('fill', '#FFFFFF')
  4508. child.set('opacity', '1.0')
  4509. child.set('stroke', '#FFFFFF')
  4510. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  4511. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  4512. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  4513. first_svg_elem_tag = 'rect'
  4514. first_svg_elem_attribs = {
  4515. 'x': minx,
  4516. 'y': miny_rect,
  4517. 'width': svgwidth,
  4518. 'height': svgheight,
  4519. 'id': 'neg_rect',
  4520. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  4521. }
  4522. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  4523. exported_svg = ET.tostring(root)
  4524. svg_elem = svg_header + str(exported_svg) + svg_footer
  4525. self.progress.emit(80)
  4526. # Parse the xml through a xml parser just to add line feeds
  4527. # and to make it look more pretty for the output
  4528. doc = parse_xml_string(svg_elem)
  4529. with open(filename, 'w') as fp:
  4530. fp.write(doc.toprettyxml())
  4531. self.progress.emit(100)
  4532. self.file_saved.emit("SVG", filename)
  4533. self.inform.emit("[success] SVG file exported to " + filename)
  4534. if use_thread is True:
  4535. proc = self.proc_container.new("Generating Film ... Please wait.")
  4536. def job_thread_film(app_obj):
  4537. try:
  4538. make_negative_film()
  4539. except Exception as e:
  4540. proc.done()
  4541. return
  4542. proc.done()
  4543. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4544. else:
  4545. make_negative_film()
  4546. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  4547. """
  4548. Exports a Geometry Object to an SVG file in negative.
  4549. :param filename: Path to the SVG file to save to.
  4550. :param: use_thread: If True use threads
  4551. :type: Bool
  4552. :return:
  4553. """
  4554. self.report_usage("export_svg_black()")
  4555. if filename is None:
  4556. filename = self.defaults["global_last_save_folder"]
  4557. self.log.debug("export_svg() black")
  4558. try:
  4559. obj = self.collection.get_by_name(str(obj_name))
  4560. except:
  4561. # TODO: The return behavior has not been established... should raise exception?
  4562. return "Could not retrieve object: %s" % obj_name
  4563. try:
  4564. box = self.collection.get_by_name(str(box_name))
  4565. except:
  4566. # TODO: The return behavior has not been established... should raise exception?
  4567. return "Could not retrieve object: %s" % box_name
  4568. if box is None:
  4569. self.inform.emit("[WARNING_NOTCL]No object Box. Using instead %s" % obj)
  4570. box = obj
  4571. def make_black_film():
  4572. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4573. self.progress.emit(40)
  4574. # Change the attributes of the exported SVG
  4575. # We don't need stroke-width
  4576. # We set opacity to maximum
  4577. # We set the colour to WHITE
  4578. root = ET.fromstring(exported_svg)
  4579. for child in root:
  4580. child.set('fill', '#000000')
  4581. child.set('opacity', '1.0')
  4582. child.set('stroke', '#000000')
  4583. exported_svg = ET.tostring(root)
  4584. # Determine bounding area for svg export
  4585. bounds = box.bounds()
  4586. size = box.size()
  4587. # This contain the measure units
  4588. uom = obj.units.lower()
  4589. # Define a boundary around SVG of about 1.0mm (~39mils)
  4590. if uom in "mm":
  4591. boundary = 1.0
  4592. else:
  4593. boundary = 0.0393701
  4594. self.progress.emit(80)
  4595. # Convert everything to strings for use in the xml doc
  4596. svgwidth = str(size[0] + (2 * boundary))
  4597. svgheight = str(size[1] + (2 * boundary))
  4598. minx = str(bounds[0] - boundary)
  4599. miny = str(bounds[1] + boundary + size[1])
  4600. self.log.debug(minx)
  4601. self.log.debug(miny)
  4602. # Add a SVG Header and footer to the svg output from shapely
  4603. # The transform flips the Y Axis so that everything renders
  4604. # properly within svg apps such as inkscape
  4605. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4606. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4607. svg_header += 'width="' + svgwidth + uom + '" '
  4608. svg_header += 'height="' + svgheight + uom + '" '
  4609. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4610. svg_header += '>'
  4611. svg_header += '<g transform="scale(1,-1)">'
  4612. svg_footer = '</g> </svg>'
  4613. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  4614. self.progress.emit(90)
  4615. # Parse the xml through a xml parser just to add line feeds
  4616. # and to make it look more pretty for the output
  4617. doc = parse_xml_string(svg_elem)
  4618. with open(filename, 'w') as fp:
  4619. fp.write(doc.toprettyxml())
  4620. self.progress.emit(100)
  4621. self.file_saved.emit("SVG", filename)
  4622. self.inform.emit("[success] SVG file exported to " + filename)
  4623. if use_thread is True:
  4624. proc = self.proc_container.new("Generating Film ... Please wait.")
  4625. def job_thread_film(app_obj):
  4626. try:
  4627. make_black_film()
  4628. except Exception as e:
  4629. proc.done()
  4630. return
  4631. proc.done()
  4632. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4633. else:
  4634. make_black_film()
  4635. def export_excellon(self, obj_name, filename, altium_format=None, use_thread=True):
  4636. """
  4637. Exports a Geometry Object to an Excellon file.
  4638. :param filename: Path to the Excellon file to save to.
  4639. :return:
  4640. """
  4641. self.report_usage("export_excellon()")
  4642. if filename is None:
  4643. filename = self.defaults["global_last_save_folder"]
  4644. self.log.debug("export_excellon()")
  4645. format_exc = ';FILE_FORMAT=2:4\n'
  4646. units = ''
  4647. try:
  4648. obj = self.collection.get_by_name(str(obj_name))
  4649. except:
  4650. # TODO: The return behavior has not been established... should raise exception?
  4651. return "Could not retrieve object: %s" % obj_name
  4652. # updated units
  4653. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4654. if units == 'IN' or units == 'INCH':
  4655. units = 'INCH'
  4656. elif units == 'MM' or units == 'METRIC':
  4657. units ='METRIC'
  4658. def make_excellon():
  4659. try:
  4660. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4661. header = 'M48\n'
  4662. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4663. (str(self.app.version), str(self.app.version_date))
  4664. header += ';Filename: %s' % str(obj_name) + '\n'
  4665. header += ';Created on : %s' % time_str + '\n'
  4666. if altium_format == None:
  4667. has_slots, excellon_code = obj.export_excellon()
  4668. header += units + '\n'
  4669. for tool in obj.tools:
  4670. if units == 'METRIC':
  4671. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.2f' % float(obj.tools[tool]['C']) + '\n'
  4672. else:
  4673. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  4674. else:
  4675. has_slots, excellon_code = obj.export_excellon_altium()
  4676. header += 'INCH,LZ\n'
  4677. header += format_exc
  4678. for tool in obj.tools:
  4679. if units == 'METRIC':
  4680. header += 'T' + str(tool) + 'F00S00' + 'C' + \
  4681. '%.4f' % (float(obj.tools[tool]['C']) / 25.4) + '\n'
  4682. else:
  4683. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  4684. header += '%\n'
  4685. footer = 'M30\n'
  4686. exported_excellon = header
  4687. exported_excellon += excellon_code
  4688. exported_excellon += footer
  4689. with open(filename, 'w') as fp:
  4690. fp.write(exported_excellon)
  4691. self.file_saved.emit("Excellon", filename)
  4692. self.inform.emit("[success] Excellon file exported to " + filename)
  4693. except:
  4694. return 'fail'
  4695. if use_thread is True:
  4696. with self.proc_container.new("Exporting Excellon") as proc:
  4697. def job_thread_exc(app_obj):
  4698. ret = make_excellon()
  4699. if ret == 'fail':
  4700. self.inform.emit('[ERROR_NOTCL] Could not export Excellon file.')
  4701. return
  4702. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4703. else:
  4704. ret = make_excellon()
  4705. if ret == 'fail':
  4706. self.inform.emit('[ERROR_NOTCL] Could not export Excellon file.')
  4707. return
  4708. def export_dxf(self, obj_name, filename, use_thread=True):
  4709. """
  4710. Exports a Geometry Object to an DXF file.
  4711. :param filename: Path to the DXF file to save to.
  4712. :return:
  4713. """
  4714. self.report_usage("export_dxf()")
  4715. if filename is None:
  4716. filename = self.defaults["global_last_save_folder"]
  4717. self.log.debug("export_dxf()")
  4718. format_exc = ''
  4719. units = ''
  4720. try:
  4721. obj = self.collection.get_by_name(str(obj_name))
  4722. except:
  4723. # TODO: The return behavior has not been established... should raise exception?
  4724. return "Could not retrieve object: %s" % obj_name
  4725. # updated units
  4726. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4727. if units == 'IN' or units == 'INCH':
  4728. units = 'INCH'
  4729. elif units == 'MM' or units == 'METIRC':
  4730. units ='METRIC'
  4731. def make_dxf():
  4732. try:
  4733. dxf_code = obj.export_dxf()
  4734. dxf_code.saveas(filename)
  4735. self.file_saved.emit("DXF", filename)
  4736. self.inform.emit("[success] DXF file exported to " + filename)
  4737. except:
  4738. return 'fail'
  4739. if use_thread is True:
  4740. with self.proc_container.new("Exporting DXF") as proc:
  4741. def job_thread_exc(app_obj):
  4742. ret = make_dxf()
  4743. if ret == 'fail':
  4744. self.inform.emit('[[WARNING_NOTCL]] Could not export DXF file.')
  4745. return
  4746. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4747. else:
  4748. ret = make_dxf()
  4749. if ret == 'fail':
  4750. self.inform.emit('[[WARNING_NOTCL]] Could not export DXF file.')
  4751. return
  4752. def import_svg(self, filename, geo_type='geometry', outname=None):
  4753. """
  4754. Adds a new Geometry Object to the projects and populates
  4755. it with shapes extracted from the SVG file.
  4756. :param filename: Path to the SVG file.
  4757. :param outname:
  4758. :return:
  4759. """
  4760. self.report_usage("import_svg()")
  4761. obj_type = ""
  4762. if geo_type is None or geo_type == "geometry":
  4763. obj_type = "geometry"
  4764. elif geo_type == "gerber":
  4765. obj_type = geo_type
  4766. else:
  4767. self.inform.emit("[ERROR_NOTCL] Not supported type was choosed as parameter. "
  4768. "Only Geometry and Gerber are supported")
  4769. return
  4770. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4771. def obj_init(geo_obj, app_obj):
  4772. geo_obj.import_svg(filename, obj_type, units=units)
  4773. geo_obj.multigeo = False
  4774. with self.proc_container.new("Importing SVG") as proc:
  4775. # Object name
  4776. name = outname or filename.split('/')[-1].split('\\')[-1]
  4777. self.new_object(obj_type, name, obj_init, autoselected=False)
  4778. self.progress.emit(20)
  4779. # Register recent file
  4780. self.file_opened.emit("svg", filename)
  4781. # GUI feedback
  4782. self.inform.emit("[success] Opened: " + filename)
  4783. self.progress.emit(100)
  4784. def import_dxf(self, filename, geo_type='geometry', outname=None):
  4785. """
  4786. Adds a new Geometry Object to the projects and populates
  4787. it with shapes extracted from the DXF file.
  4788. :param filename: Path to the DXF file.
  4789. :param outname:
  4790. :type putname: str
  4791. :return:
  4792. """
  4793. self.report_usage("import_dxf()")
  4794. obj_type = ""
  4795. if geo_type is None or geo_type == "geometry":
  4796. obj_type = "geometry"
  4797. elif geo_type == "gerber":
  4798. obj_type = geo_type
  4799. else:
  4800. self.inform.emit("[ERROR_NOTCL] Not supported type was choosed as parameter. "
  4801. "Only Geometry and Gerber are supported")
  4802. return
  4803. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4804. def obj_init(geo_obj, app_obj):
  4805. geo_obj.import_dxf(filename, obj_type, units=units)
  4806. geo_obj.multigeo = False
  4807. with self.proc_container.new("Importing DXF") as proc:
  4808. # Object name
  4809. name = outname or filename.split('/')[-1].split('\\')[-1]
  4810. self.new_object(obj_type, name, obj_init, autoselected=False)
  4811. self.progress.emit(20)
  4812. # Register recent file
  4813. self.file_opened.emit("dxf", filename)
  4814. # GUI feedback
  4815. self.inform.emit("[success] Opened: " + filename)
  4816. self.progress.emit(100)
  4817. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  4818. """
  4819. Adds a new Geometry Object to the projects and populates
  4820. it with shapes extracted from the SVG file.
  4821. :param filename: Path to the SVG file.
  4822. :param outname:
  4823. :return:
  4824. """
  4825. self.report_usage("import_image()")
  4826. obj_type = ""
  4827. if type is None or type == "geometry":
  4828. obj_type = "geometry"
  4829. elif type == "gerber":
  4830. obj_type = type
  4831. else:
  4832. self.inform.emit("[ERROR_NOTCL] Not supported type was picked as parameter. "
  4833. "Only Geometry and Gerber are supported")
  4834. return
  4835. def obj_init(geo_obj, app_obj):
  4836. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  4837. geo_obj.multigeo = False
  4838. with self.proc_container.new("Importing Image") as proc:
  4839. # Object name
  4840. name = outname or filename.split('/')[-1].split('\\')[-1]
  4841. units = self.general_options_form.general_app_group.units_radio.get_value()
  4842. self.new_object(obj_type, name, obj_init)
  4843. self.progress.emit(20)
  4844. # Register recent file
  4845. self.file_opened.emit("image", filename)
  4846. # GUI feedback
  4847. self.inform.emit("[success] Opened: " + filename)
  4848. self.progress.emit(100)
  4849. def open_gerber(self, filename, follow=False, outname=None):
  4850. """
  4851. Opens a Gerber file, parses it and creates a new object for
  4852. it in the program. Thread-safe.
  4853. :param outname: Name of the resulting object. None causes the
  4854. name to be that of the file.
  4855. :param filename: Gerber file filename
  4856. :type filename: str
  4857. :param follow: If true, the parser will not create polygons, just lines
  4858. following the gerber path.
  4859. :type follow: bool
  4860. :return: None
  4861. """
  4862. # How the object should be initialized
  4863. def obj_init(gerber_obj, app_obj):
  4864. assert isinstance(gerber_obj, FlatCAMGerber), \
  4865. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  4866. # Opening the file happens here
  4867. self.progress.emit(30)
  4868. try:
  4869. gerber_obj.parse_file(filename, follow=follow)
  4870. except IOError:
  4871. app_obj.inform.emit("[ERROR_NOTCL] Failed to open file: " + filename)
  4872. app_obj.progress.emit(0)
  4873. self.inform.emit('[ERROR_NOTCL] Failed to open file: ' + filename)
  4874. return "fail"
  4875. except ParseError as err:
  4876. app_obj.inform.emit("[ERROR_NOTCL] Failed to parse file: " + filename + ". " + str(err))
  4877. app_obj.progress.emit(0)
  4878. self.log.error(str(err))
  4879. return "fail"
  4880. except:
  4881. msg = "[ERROR] An internal error has ocurred. See shell.\n"
  4882. msg += traceback.format_exc()
  4883. app_obj.inform.emit(msg)
  4884. return "fail"
  4885. if gerber_obj.is_empty():
  4886. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  4887. # self.collection.set_active(gerber_obj.options["name"])
  4888. # self.collection.delete_active()
  4889. self.inform.emit("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation.")
  4890. return "fail"
  4891. # Further parsing
  4892. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  4893. if follow is False:
  4894. App.log.debug("open_gerber()")
  4895. else:
  4896. App.log.debug("open_gerber() with 'follow' attribute")
  4897. with self.proc_container.new("Opening Gerber") as proc:
  4898. self.progress.emit(10)
  4899. # Object name
  4900. name = outname or filename.split('/')[-1].split('\\')[-1]
  4901. ### Object creation ###
  4902. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  4903. if ret == 'fail':
  4904. self.inform.emit('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.')
  4905. return
  4906. # Register recent file
  4907. self.file_opened.emit("gerber", filename)
  4908. self.progress.emit(100)
  4909. # GUI feedback
  4910. self.inform.emit("[success] Opened: " + filename)
  4911. def open_excellon(self, filename, outname=None):
  4912. """
  4913. Opens an Excellon file, parses it and creates a new object for
  4914. it in the program. Thread-safe.
  4915. :param outname: Name of the resulting object. None causes the
  4916. name to be that of the file.
  4917. :param filename: Excellon file filename
  4918. :type filename: str
  4919. :return: None
  4920. """
  4921. App.log.debug("open_excellon()")
  4922. #self.progress.emit(10)
  4923. # How the object should be initialized
  4924. def obj_init(excellon_obj, app_obj):
  4925. # self.progress.emit(20)
  4926. try:
  4927. ret = excellon_obj.parse_file(filename)
  4928. if ret == "fail":
  4929. log.debug("Excellon parsing failed.")
  4930. self.inform.emit("[ERROR_NOTCL] This is not Excellon file.")
  4931. return "fail"
  4932. except IOError:
  4933. app_obj.inform.emit("[ERROR_NOTCL] Cannot open file: " + filename)
  4934. log.debug("Could not open Excellon object.")
  4935. self.progress.emit(0) # TODO: self and app_bjj mixed
  4936. return "fail"
  4937. except:
  4938. msg = "[ERROR_NOTCL] An internal error has occurred. See shell.\n"
  4939. msg += traceback.format_exc()
  4940. app_obj.inform.emit(msg)
  4941. return "fail"
  4942. ret = excellon_obj.create_geometry()
  4943. if ret == 'fail':
  4944. log.debug("Could not create geometry for Excellon object.")
  4945. return "fail"
  4946. if excellon_obj.is_empty():
  4947. app_obj.inform.emit("[ERROR_NOTCL] No geometry found in file: " + filename)
  4948. return "fail"
  4949. with self.proc_container.new("Opening Excellon."):
  4950. # Object name
  4951. name = outname or filename.split('/')[-1].split('\\')[-1]
  4952. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  4953. if ret == 'fail':
  4954. self.inform.emit('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.')
  4955. return
  4956. # Register recent file
  4957. self.file_opened.emit("excellon", filename)
  4958. # GUI feedback
  4959. self.inform.emit("[success] Opened: " + filename)
  4960. # self.progress.emit(100)
  4961. def open_gcode(self, filename, outname=None):
  4962. """
  4963. Opens a G-gcode file, parses it and creates a new object for
  4964. it in the program. Thread-safe.
  4965. :param outname: Name of the resulting object. None causes the
  4966. name to be that of the file.
  4967. :param filename: G-code file filename
  4968. :type filename: str
  4969. :return: None
  4970. """
  4971. App.log.debug("open_gcode()")
  4972. # How the object should be initialized
  4973. def obj_init(job_obj, app_obj_):
  4974. """
  4975. :type app_obj_: App
  4976. """
  4977. assert isinstance(app_obj_, App), \
  4978. "Initializer expected App, got %s" % type(app_obj_)
  4979. self.progress.emit(10)
  4980. try:
  4981. f = open(filename)
  4982. gcode = f.read()
  4983. f.close()
  4984. except IOError:
  4985. app_obj_.inform.emit("[ERROR_NOTCL] Failed to open " + filename)
  4986. self.progress.emit(0)
  4987. return "fail"
  4988. job_obj.gcode = gcode
  4989. self.progress.emit(20)
  4990. ret = job_obj.gcode_parse()
  4991. if ret == "fail":
  4992. self.inform.emit("[ERROR_NOTCL] This is not GCODE")
  4993. return "fail"
  4994. self.progress.emit(60)
  4995. job_obj.create_geometry()
  4996. with self.proc_container.new("Opening G-Code."):
  4997. # Object name
  4998. name = outname or filename.split('/')[-1].split('\\')[-1]
  4999. # New object creation and file processing
  5000. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  5001. if ret == 'fail':
  5002. self.inform.emit("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  5003. "Attempting to create a FlatCAM CNCJob Object from "
  5004. "G-Code file failed during processing")
  5005. return "fail"
  5006. # Register recent file
  5007. self.file_opened.emit("cncjob", filename)
  5008. # GUI feedback
  5009. self.inform.emit("[success] Opened: " + filename)
  5010. self.progress.emit(100)
  5011. def open_project(self, filename, run_from_arg=None):
  5012. """
  5013. Loads a project from the specified file.
  5014. 1) Loads and parses file
  5015. 2) Registers the file as recently opened.
  5016. 3) Calls on_file_new()
  5017. 4) Updates options
  5018. 5) Calls new_object() with the object's from_dict() as init method.
  5019. 6) Calls plot_all()
  5020. :param filename: Name of the file from which to load.
  5021. :type filename: str
  5022. :return: None
  5023. """
  5024. App.log.debug("Opening project: " + filename)
  5025. # Open and parse
  5026. try:
  5027. f = open(filename, 'r')
  5028. except IOError:
  5029. App.log.error("Failed to open project file: %s" % filename)
  5030. self.inform.emit("[ERROR_NOTCL] Failed to open project file: %s" % filename)
  5031. return
  5032. try:
  5033. d = json.load(f, object_hook=dict2obj)
  5034. except:
  5035. App.log.error("Failed to parse project file: %s" % filename)
  5036. self.inform.emit("[ERROR_NOTCL] Failed to parse project file: %s" % filename)
  5037. f.close()
  5038. return
  5039. self.file_opened.emit("project", filename)
  5040. # Clear the current project
  5041. ## NOT THREAD SAFE ##
  5042. if run_from_arg is True:
  5043. pass
  5044. else:
  5045. self.on_file_new()
  5046. #Project options
  5047. self.options.update(d['options'])
  5048. self.project_filename = filename
  5049. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  5050. self.set_screen_units(self.options["units"])
  5051. # Re create objects
  5052. App.log.debug("Re-creating objects...")
  5053. for obj in d['objs']:
  5054. def obj_init(obj_inst, app_inst):
  5055. obj_inst.from_dict(obj)
  5056. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  5057. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  5058. # self.plot_all()
  5059. self.inform.emit("[success] Project loaded from: " + filename)
  5060. App.log.debug("Project loaded")
  5061. def propagate_defaults(self, silent=False):
  5062. """
  5063. This method is used to set default values in classes. It's
  5064. an alternative to project options but allows the use
  5065. of values invisible to the user.
  5066. :return: None
  5067. """
  5068. if silent is False:
  5069. self.log.debug("propagate_defaults()")
  5070. # Which objects to update the given parameters.
  5071. routes = {
  5072. "global_zdownrate": CNCjob,
  5073. "excellon_zeros": Excellon,
  5074. "excellon_format_upper_in": Excellon,
  5075. "excellon_format_lower_in": Excellon,
  5076. "excellon_format_upper_mm": Excellon,
  5077. "excellon_format_lower_mm": Excellon,
  5078. "excellon_units": Excellon,
  5079. "gerber_use_buffer_for_union": Gerber,
  5080. "geometry_multidepth": Geometry
  5081. }
  5082. for param in routes:
  5083. if param in routes[param].defaults:
  5084. try:
  5085. routes[param].defaults[param] = self.defaults[param]
  5086. if silent is False:
  5087. self.log.debug(" " + param + " OK")
  5088. except KeyError:
  5089. if silent is False:
  5090. self.log.debug(" ERROR: " + param + " not in defaults.")
  5091. else:
  5092. # Try extracting the name:
  5093. # classname_param here is param in the object
  5094. if param.find(routes[param].__name__.lower() + "_") == 0:
  5095. p = param[len(routes[param].__name__) + 1:]
  5096. if p in routes[param].defaults:
  5097. routes[param].defaults[p] = self.defaults[param]
  5098. if silent is False:
  5099. self.log.debug(" " + param + " OK!")
  5100. def restore_main_win_geom(self):
  5101. try:
  5102. self.ui.setGeometry(self.defaults["global_def_win_x"],
  5103. self.defaults["global_def_win_y"],
  5104. self.defaults["global_def_win_w"],
  5105. self.defaults["global_def_win_h"])
  5106. self.ui.splitter.setSizes([self.defaults["def_notebook_width"], 0])
  5107. except KeyError:
  5108. pass
  5109. def plot_all(self, zoom=True):
  5110. """
  5111. Re-generates all plots from all objects.
  5112. :return: None
  5113. """
  5114. self.log.debug("Plot_all()")
  5115. for obj in self.collection.get_list():
  5116. def worker_task(obj):
  5117. with self.proc_container.new("Plotting"):
  5118. obj.plot()
  5119. if zoom:
  5120. self.object_plotted.emit(obj)
  5121. # Send to worker
  5122. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  5123. # self.progress.emit(10)
  5124. #
  5125. # def worker_task(app_obj):
  5126. # print "worker task"
  5127. # percentage = 0.1
  5128. # try:
  5129. # delta = 0.9 / len(self.collection.get_list())
  5130. # except ZeroDivisionError:
  5131. # self.progress.emit(0)
  5132. # return
  5133. # for obj in self.collection.get_list():
  5134. # with self.proc_container.new("Plotting"):
  5135. # obj.plot()
  5136. # app_obj.object_plotted.emit(obj)
  5137. #
  5138. # percentage += delta
  5139. # self.progress.emit(int(percentage*100))
  5140. #
  5141. # self.progress.emit(0)
  5142. # self.plots_updated.emit()
  5143. #
  5144. # # Send to worker
  5145. # #self.worker.add_task(worker_task, [self])
  5146. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5147. def register_folder(self, filename):
  5148. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  5149. def register_save_folder(self, filename):
  5150. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  5151. def set_progress_bar(self, percentage, text=""):
  5152. self.ui.progress_bar.setValue(int(percentage))
  5153. def setup_shell(self):
  5154. """
  5155. Creates shell functions. Runs once at startup.
  5156. :return: None
  5157. """
  5158. self.log.debug("setup_shell()")
  5159. def shelp(p=None):
  5160. if not p:
  5161. return "Available commands:\n" + \
  5162. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  5163. "\n\nType help <command_name> for usage.\n Example: help open_gerber"
  5164. if p not in commands:
  5165. return "Unknown command: %s" % p
  5166. return commands[p]["help"]
  5167. # --- Migrated to new architecture ---
  5168. # def options(name):
  5169. # ops = self.collection.get_by_name(str(name)).options
  5170. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  5171. def h(*args):
  5172. """
  5173. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  5174. and standalone parameters into list.
  5175. """
  5176. kwa = {}
  5177. a = []
  5178. n = len(args)
  5179. name = None
  5180. for i in range(n):
  5181. match = re.search(r'^-([a-zA-Z].*)', args[i])
  5182. if match:
  5183. assert name is None
  5184. name = match.group(1)
  5185. continue
  5186. if name is None:
  5187. a.append(args[i])
  5188. else:
  5189. kwa[name] = args[i]
  5190. name = None
  5191. return a, kwa
  5192. @contextmanager
  5193. def wait_signal(signal, timeout=10000):
  5194. """
  5195. Block loop until signal emitted, timeout (ms) elapses
  5196. or unhandled exception happens in a thread.
  5197. :param signal: Signal to wait for.
  5198. """
  5199. loop = QtCore.QEventLoop()
  5200. # Normal termination
  5201. signal.connect(loop.quit)
  5202. # Termination by exception in thread
  5203. self.thread_exception.connect(loop.quit)
  5204. status = {'timed_out': False}
  5205. def report_quit():
  5206. status['timed_out'] = True
  5207. loop.quit()
  5208. yield
  5209. # Temporarily change how exceptions are managed.
  5210. oeh = sys.excepthook
  5211. ex = []
  5212. def except_hook(type_, value, traceback_):
  5213. ex.append(value)
  5214. oeh(type_, value, traceback_)
  5215. sys.excepthook = except_hook
  5216. # Terminate on timeout
  5217. if timeout is not None:
  5218. QtCore.QTimer.singleShot(timeout, report_quit)
  5219. #### Block ####
  5220. loop.exec_()
  5221. # Restore exception management
  5222. sys.excepthook = oeh
  5223. if ex:
  5224. self.raiseTclError(str(ex[0]))
  5225. if status['timed_out']:
  5226. raise Exception('Timed out!')
  5227. def make_docs():
  5228. output = ''
  5229. import collections
  5230. od = collections.OrderedDict(sorted(commands.items()))
  5231. for cmd_, val in od.items():
  5232. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  5233. t = val['help']
  5234. usage_i = t.find('>')
  5235. if usage_i < 0:
  5236. expl = t
  5237. output += expl + '\n\n'
  5238. continue
  5239. expl = t[:usage_i - 1]
  5240. output += expl + '\n\n'
  5241. end_usage_i = t[usage_i:].find('\n')
  5242. if end_usage_i < 0:
  5243. end_usage_i = len(t[usage_i:])
  5244. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  5245. else:
  5246. extras = t[usage_i+end_usage_i+1:]
  5247. parts = [s.strip() for s in extras.split('\n')]
  5248. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  5249. for p in parts:
  5250. output += ' ' + p + '\n\n'
  5251. return output
  5252. '''
  5253. Howto implement TCL shell commands:
  5254. All parameters passed to command should be possible to set as None and test it afterwards.
  5255. This is because we need to see error caused in tcl,
  5256. if None value as default parameter is not allowed TCL will return empty error.
  5257. Use:
  5258. def mycommand(name=None,...):
  5259. Test it like this:
  5260. if name is None:
  5261. self.raise_tcl_error('Argument name is missing.')
  5262. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  5263. otherwise we will miss it and processing will silently continue.
  5264. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  5265. which is catched in exec_command and displayed in TCL shell console with red background.
  5266. Error in console is displayed with TCL trace.
  5267. This behavior works only within main thread,
  5268. errors with promissed tasks can be catched and detected only with log.
  5269. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  5270. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  5271. '''
  5272. commands = {
  5273. 'help': {
  5274. 'fcn': shelp,
  5275. 'help': "Shows list of commands."
  5276. },
  5277. }
  5278. # Import/overwrite tcl commands as objects of TclCommand descendants
  5279. # This modifies the variable 'commands'.
  5280. tclCommands.register_all_commands(self, commands)
  5281. # Add commands to the tcl interpreter
  5282. for cmd in commands:
  5283. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  5284. # Make the tcl puts function return instead of print to stdout
  5285. self.tcl.eval('''
  5286. rename puts original_puts
  5287. proc puts {args} {
  5288. if {[llength $args] == 1} {
  5289. return "[lindex $args 0]"
  5290. } else {
  5291. eval original_puts $args
  5292. }
  5293. }
  5294. ''')
  5295. def setup_recent_items(self):
  5296. # TODO: Move this to constructor
  5297. icons = {
  5298. "gerber": "share/flatcam_icon16.png",
  5299. "excellon": "share/drill16.png",
  5300. "cncjob": "share/cnc16.png",
  5301. "project": "share/project16.png",
  5302. "svg": "share/geometry16.png",
  5303. "dxf": "share/dxf16.png",
  5304. "image": "share/image16.png"
  5305. }
  5306. openers = {
  5307. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  5308. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  5309. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  5310. 'project': self.open_project,
  5311. 'svg': self.import_svg,
  5312. 'dxf': self.import_dxf,
  5313. 'image': self.import_image
  5314. }
  5315. # Open file
  5316. try:
  5317. f = open(self.data_path + '/recent.json')
  5318. except IOError:
  5319. App.log.error("Failed to load recent item list.")
  5320. self.inform.emit("[ERROR_NOTCL] Failed to load recent item list.")
  5321. return
  5322. try:
  5323. self.recent = json.load(f)
  5324. except json.scanner.JSONDecodeError:
  5325. App.log.error("Failed to parse recent item list.")
  5326. self.inform.emit("[ERROR_NOTCL] Failed to parse recent item list.")
  5327. f.close()
  5328. return
  5329. f.close()
  5330. # Closure needed to create callbacks in a loop.
  5331. # Otherwise late binding occurs.
  5332. def make_callback(func, fname):
  5333. def opener():
  5334. func(fname)
  5335. return opener
  5336. def reset_recent():
  5337. # Reset menu
  5338. self.ui.recent.clear()
  5339. self.recent = []
  5340. try:
  5341. f = open(self.data_path + '/recent.json', 'w')
  5342. except IOError:
  5343. App.log.error("Failed to open recent items file for writing.")
  5344. return
  5345. json.dump(self.recent, f)
  5346. # Reset menu
  5347. self.ui.recent.clear()
  5348. # Create menu items
  5349. for recent in self.recent:
  5350. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5351. try:
  5352. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5353. # Attach callback
  5354. o = make_callback(openers[recent["kind"]], recent['filename'])
  5355. action.triggered.connect(o)
  5356. self.ui.recent.addAction(action)
  5357. except KeyError:
  5358. App.log.error("Unsupported file type: %s" % recent["kind"])
  5359. # Last action in Recent Files menu is one that Clear the content
  5360. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  5361. clear_action.triggered.connect(reset_recent)
  5362. self.ui.recent.addSeparator()
  5363. self.ui.recent.addAction(clear_action)
  5364. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  5365. # self.ui.menufilerecent.set_submenu(recent_menu)
  5366. # recent_menu.show_all()
  5367. # self.ui.recent.show()
  5368. self.log.debug("Recent items list has been populated.")
  5369. def setup_component_editor(self):
  5370. # label = QtWidgets.QLabel("Choose an item from Project")
  5371. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  5372. sel_title = QtWidgets.QTextEdit(
  5373. '<b>Shortcut Key List</b>')
  5374. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5375. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5376. # font = self.sel_title.font()
  5377. # font.setPointSize(12)
  5378. # self.sel_title.setFont(font)
  5379. selected_text = '''
  5380. <p><span style="font-size:14px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  5381. <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5382. The normal flow when working in FlatCAM is the following:</span></p>
  5383. <ol>
  5384. <li><span style="font-size:10px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  5385. <br />
  5386. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  5387. &nbsp;</li>
  5388. <li><span style="font-size:10px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  5389. <br />
  5390. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  5391. <br />
  5392. You can change the parameters in this screen and the flow direction is like this:<br />
  5393. <br />
  5394. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  5395. </ol>
  5396. <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  5397. '''
  5398. sel_title.setText(selected_text)
  5399. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5400. self.ui.selected_scroll_area.setWidget(sel_title)
  5401. # tool_title = QtWidgets.QTextEdit(
  5402. # '<b>Shortcut Key List</b>')
  5403. # tool_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5404. # tool_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5405. # # font = self.sel_title.font()
  5406. # # font.setPointSize(12)
  5407. # # self.sel_title.setFont(font)
  5408. #
  5409. # tool_text = '''
  5410. # <p><span style="font-size:14px"><strong>Tool Tab - Choose an Item in Tools Menu</strong></span></p>
  5411. #
  5412. # <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5413. # Some of the functionality of FlatCAM have been implemented as tools (a sort of plugins). </span></p>
  5414. #
  5415. # <p><span style="font-size:10px">Most of the tools are accessible through&nbsp;the Tools menu or by using the associated shortcut keys.<br />
  5416. # Each such a tool, if it needs an object to be used as a source it will provide the way to select this object(s) through a series of comboboxes. The result of using a tool is either a Geometry, an information that can be used in the app or it can be a file that can be saved.</span></p>
  5417. #
  5418. # <ol>
  5419. # </ol>
  5420. #
  5421. # <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: &#39;`&#39; (key left to 1).</span></p>
  5422. #
  5423. # '''
  5424. #
  5425. # tool_title.setText(tool_text)
  5426. # tool_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5427. #
  5428. # self.ui.tool_scroll_area.setWidget(tool_title)
  5429. def setup_obj_classes(self):
  5430. """
  5431. Sets up application specifics on the FlatCAMObj class.
  5432. :return: None
  5433. """
  5434. FlatCAMObj.app = self
  5435. ObjectCollection.app = self
  5436. FCProcess.app = self
  5437. FCProcessContainer.app = self
  5438. def version_check(self):
  5439. """
  5440. Checks for the latest version of the program. Alerts the
  5441. user if theirs is outdated. This method is meant to be run
  5442. in a separate thread.
  5443. :return: None
  5444. """
  5445. self.log.debug("version_check()")
  5446. if self.general_defaults_form.general_gui_group.send_stats_cb.get_value() is True:
  5447. full_url = App.version_url + \
  5448. "?s=" + str(self.defaults['global_serial']) + \
  5449. "&v=" + str(self.version) + \
  5450. "&os=" + str(self.os) + \
  5451. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  5452. else:
  5453. # no_stats dict; just so it won't break things on website
  5454. no_ststs_dict = {}
  5455. no_ststs_dict["global_ststs"] = {}
  5456. full_url = App.version_url + \
  5457. "?s=" + str(self.defaults['global_serial']) + \
  5458. "&v=" + str(self.version) + \
  5459. "&os=" + str(self.os) + \
  5460. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  5461. App.log.debug("Checking for updates @ %s" % full_url)
  5462. ### Get the data
  5463. try:
  5464. f = urllib.request.urlopen(full_url)
  5465. except:
  5466. # App.log.warning("Failed checking for latest version. Could not connect.")
  5467. self.log.warning("Failed checking for latest version. Could not connect.")
  5468. self.inform.emit("[WARNING_NOTCL] Failed checking for latest version. Could not connect.")
  5469. return
  5470. try:
  5471. data = json.load(f)
  5472. except Exception as e:
  5473. App.log.error("Could not parse information about latest version.")
  5474. self.inform.emit("[ERROR_NOTCL] Could not parse information about latest version.")
  5475. App.log.debug("json.load(): %s" % str(e))
  5476. f.close()
  5477. return
  5478. f.close()
  5479. ### Latest version?
  5480. if self.version >= data["version"]:
  5481. App.log.debug("FlatCAM is up to date!")
  5482. self.inform.emit("[success] FlatCAM is up to date!")
  5483. return
  5484. App.log.debug("Newer version available.")
  5485. self.message.emit(
  5486. "Newer Version Available",
  5487. str("There is a newer version of FlatCAM " +
  5488. "available for download:<br><br>" +
  5489. "<B>" + data["name"] + "</b><br>" +
  5490. data["message"].replace("\n", "<br>")),
  5491. "info"
  5492. )
  5493. def on_zoom_fit(self, event):
  5494. """
  5495. Callback for zoom-out request. This can be either from the corresponding
  5496. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  5497. with axes limits from the geometry bounds of all objects.
  5498. :param event: Ignored.
  5499. :return: None
  5500. """
  5501. self.plotcanvas.fit_view()
  5502. def disable_all_plots(self):
  5503. self.report_usage("disable_all_plots()")
  5504. self.disable_plots(self.collection.get_list())
  5505. self.inform.emit("[success]All plots disabled.")
  5506. def disable_other_plots(self):
  5507. self.report_usage("disable_other_plots()")
  5508. self.disable_plots(self.collection.get_non_selected())
  5509. self.inform.emit("[success]All non selected plots disabled.")
  5510. def enable_all_plots(self):
  5511. self.report_usage("enable_all_plots()")
  5512. self.enable_plots(self.collection.get_list())
  5513. self.inform.emit("[success]All plots enabled.")
  5514. # TODO: FIX THIS
  5515. '''
  5516. By default this is not threaded
  5517. If threaded the app give warnings like this:
  5518. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5519. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5520. '''
  5521. def enable_plots(self, objects, threaded=False):
  5522. if threaded is True:
  5523. def worker_task(app_obj):
  5524. percentage = 0.1
  5525. try:
  5526. delta = 0.9 / len(objects)
  5527. except ZeroDivisionError:
  5528. self.progress.emit(0)
  5529. return
  5530. for obj in objects:
  5531. obj.options['plot'] = True
  5532. percentage += delta
  5533. self.progress.emit(int(percentage*100))
  5534. self.progress.emit(0)
  5535. self.plots_updated.emit()
  5536. self.collection.update_view()
  5537. # Send to worker
  5538. # self.worker.add_task(worker_task, [self])
  5539. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5540. else:
  5541. for obj in objects:
  5542. obj.options['plot'] = True
  5543. self.progress.emit(0)
  5544. self.plots_updated.emit()
  5545. self.collection.update_view()
  5546. # TODO: FIX THIS
  5547. '''
  5548. By default this is not threaded
  5549. If threaded the app give warnings like this:
  5550. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5551. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5552. '''
  5553. def disable_plots(self, objects, threaded=False):
  5554. # TODO: This method is very similar to replot_all. Try to merge.
  5555. """
  5556. Disables plots
  5557. :param objects: list
  5558. Objects to be disabled
  5559. :return:
  5560. """
  5561. if threaded is True:
  5562. self.progress.emit(10)
  5563. def worker_task(app_obj):
  5564. percentage = 0.1
  5565. try:
  5566. delta = 0.9 / len(objects)
  5567. except ZeroDivisionError:
  5568. self.progress.emit(0)
  5569. return
  5570. for obj in objects:
  5571. obj.options['plot'] = False
  5572. percentage += delta
  5573. self.progress.emit(int(percentage*100))
  5574. self.progress.emit(0)
  5575. self.plots_updated.emit()
  5576. self.collection.update_view()
  5577. # Send to worker
  5578. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5579. else:
  5580. for obj in objects:
  5581. obj.options['plot'] = False
  5582. self.plots_updated.emit()
  5583. self.collection.update_view()
  5584. def clear_plots(self):
  5585. objects = self.collection.get_list()
  5586. for obj in objects:
  5587. obj.clear(obj == objects[-1])
  5588. # Clear pool to free memory
  5589. self.clear_pool()
  5590. def generate_cnc_job(self, objects):
  5591. self.report_usage("generate_cnc_job()")
  5592. for obj in objects:
  5593. obj.generatecncjob()
  5594. def save_project(self, filename):
  5595. """
  5596. Saves the current project to the specified file.
  5597. :param filename: Name of the file in which to save.
  5598. :type filename: str
  5599. :return: None
  5600. """
  5601. self.log.debug("save_project()")
  5602. with self.proc_container.new("Saving FlatCAM Project") as proc:
  5603. ## Capture the latest changes
  5604. # Current object
  5605. try:
  5606. self.collection.get_active().read_form()
  5607. except:
  5608. self.log.debug("[WARNING] There was no active object")
  5609. pass
  5610. # Project options
  5611. self.options_read_form()
  5612. # Serialize the whole project
  5613. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  5614. "options": self.options,
  5615. "version": self.version}
  5616. # Open file
  5617. try:
  5618. f = open(filename, 'w')
  5619. except IOError:
  5620. App.log.error("[ERROR] Failed to open file for saving: %s", filename)
  5621. return
  5622. # Write
  5623. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  5624. f.close()
  5625. # verification of the saved project
  5626. # Open and parse
  5627. try:
  5628. saved_f = open(filename, 'r')
  5629. except IOError:
  5630. self.inform.emit("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it." % filename)
  5631. return
  5632. try:
  5633. saved_d = json.load(saved_f, object_hook=dict2obj)
  5634. except:
  5635. self.inform.emit("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it." % filename)
  5636. f.close()
  5637. return
  5638. saved_f.close()
  5639. if 'version' in saved_d:
  5640. self.inform.emit("[success] Project saved to: %s" % filename)
  5641. else:
  5642. self.inform.emit("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it." % filename)
  5643. def on_options_app2project(self):
  5644. """
  5645. Callback for Options->Transfer Options->App=>Project. Copies options
  5646. from application defaults to project defaults.
  5647. :return: None
  5648. """
  5649. self.report_usage("on_options_app2project")
  5650. self.defaults_read_form()
  5651. self.options.update(self.defaults)
  5652. self.options_write_form()
  5653. def on_options_project2app(self):
  5654. """
  5655. Callback for Options->Transfer Options->Project=>App. Copies options
  5656. from project defaults to application defaults.
  5657. :return: None
  5658. """
  5659. self.report_usage("on_options_project2app")
  5660. self.options_read_form()
  5661. self.defaults.update(self.options)
  5662. self.defaults_write_form()
  5663. def on_options_project2object(self):
  5664. """
  5665. Callback for Options->Transfer Options->Project=>Object. Copies options
  5666. from project defaults to the currently selected object.
  5667. :return: None
  5668. """
  5669. self.report_usage("on_options_project2object")
  5670. self.options_read_form()
  5671. obj = self.collection.get_active()
  5672. if obj is None:
  5673. self.inform.emit("WARNING: No object selected.")
  5674. return
  5675. for option in self.options:
  5676. if option.find(obj.kind + "_") == 0:
  5677. oname = option[len(obj.kind) + 1:]
  5678. obj.options[oname] = self.options[option]
  5679. obj.to_form() # Update UI
  5680. def on_options_object2project(self):
  5681. """
  5682. Callback for Options->Transfer Options->Object=>Project. Copies options
  5683. from the currently selected object to project defaults.
  5684. :return: None
  5685. """
  5686. self.report_usage("on_options_object2project")
  5687. obj = self.collection.get_active()
  5688. if obj is None:
  5689. self.inform.emit("WARNING: No object selected.")
  5690. return
  5691. obj.read_form()
  5692. for option in obj.options:
  5693. if option in ['name']: # TODO: Handle this better...
  5694. continue
  5695. self.options[obj.kind + "_" + option] = obj.options[option]
  5696. self.options_write_form()
  5697. def on_options_object2app(self):
  5698. """
  5699. Callback for Options->Transfer Options->Object=>App. Copies options
  5700. from the currently selected object to application defaults.
  5701. :return: None
  5702. """
  5703. self.report_usage("on_options_object2app")
  5704. obj = self.collection.get_active()
  5705. if obj is None:
  5706. self.inform.emit("WARNING: No object selected.")
  5707. return
  5708. obj.read_form()
  5709. for option in obj.options:
  5710. if option in ['name']: # TODO: Handle this better...
  5711. continue
  5712. self.defaults[obj.kind + "_" + option] = obj.options[option]
  5713. self.defaults_write_form()
  5714. def on_options_app2object(self):
  5715. """
  5716. Callback for Options->Transfer Options->App=>Object. Copies options
  5717. from application defaults to the currently selected object.
  5718. :return: None
  5719. """
  5720. self.report_usage("on_options_app2object")
  5721. self.defaults_read_form()
  5722. obj = self.collection.get_active()
  5723. if obj is None:
  5724. self.inform.emit("WARNING: No object selected.")
  5725. return
  5726. for option in self.defaults:
  5727. if option.find(obj.kind + "_") == 0:
  5728. oname = option[len(obj.kind) + 1:]
  5729. obj.options[oname] = self.defaults[option]
  5730. obj.to_form() # Update UI
  5731. # end of file