FlatCAMApp.py 276 KB

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