FlatCAMApp.py 320 KB

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