FlatCAMApp.py 582 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893
  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 urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. import stat
  18. from stat import S_IREAD, S_IRGRP, S_IROTH
  19. import ctypes
  20. # import tkinter as tk
  21. # from PyQt5 import QtPrintSupport
  22. from reportlab.graphics import renderPDF
  23. from reportlab.pdfgen import canvas
  24. from reportlab.graphics import renderPM
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. from contextlib import contextmanager
  29. import gc
  30. from xml.dom.minidom import parseString as parse_xml_string
  31. from multiprocessing.connection import Listener, Client
  32. from multiprocessing import Pool
  33. import socket
  34. from array import array
  35. import vispy.scene as scene
  36. # #######################################
  37. # # Imports part of FlatCAM ##
  38. # #######################################
  39. from ObjectCollection import *
  40. from FlatCAMObj import *
  41. from camlib import to_dict, dict2obj, ET, ParseError
  42. from flatcamGUI.PlotCanvas import *
  43. from flatcamGUI.PlotCanvasLegacy import *
  44. from flatcamGUI.FlatCAMGUI import *
  45. from FlatCAMCommon import LoudDict, BookmarkManager, ToolsDB, color_variant
  46. from FlatCAMPostProc import load_preprocessors
  47. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  48. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  49. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  50. from flatcamEditors.FlatCAMTextEditor import TextEditor
  51. from flatcamParsers.ParseHPGL2 import HPGL2
  52. from FlatCAMProcess import *
  53. from FlatCAMWorkerStack import WorkerStack
  54. # from flatcamGUI.VisPyVisuals import Color
  55. from vispy.gloo.util import _screenshot
  56. from vispy.io import write_png
  57. from flatcamTools import *
  58. import tclCommands
  59. import gettext
  60. import FlatCAMTranslation as fcTranslate
  61. import builtins
  62. if sys.platform == 'win32':
  63. import winreg
  64. fcTranslate.apply_language('strings')
  65. if '_' not in builtins.__dict__:
  66. _ = gettext.gettext
  67. class App(QtCore.QObject):
  68. # ########################################
  69. # # App ###
  70. # ########################################
  71. """
  72. The main application class. The constructor starts the GUI.
  73. """
  74. # Get Cmd Line Options
  75. cmd_line_shellfile = ''
  76. cmd_line_shellvar = ''
  77. cmd_line_headless = None
  78. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  79. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  80. "FlatCam.py --headless=1"
  81. try:
  82. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  83. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  84. "shellvar=",
  85. "headless=",
  86. "multiprocessing-fork="])
  87. except getopt.GetoptError:
  88. print(cmd_line_help)
  89. sys.exit(2)
  90. for opt, arg in cmd_line_options:
  91. if opt == '-h':
  92. print(cmd_line_help)
  93. sys.exit()
  94. elif opt == '--shellfile':
  95. cmd_line_shellfile = arg
  96. elif opt == '--shellvar':
  97. cmd_line_shellvar = arg
  98. elif opt == '--headless':
  99. try:
  100. cmd_line_headless = eval(arg)
  101. except NameError:
  102. pass
  103. # ## Logging ###
  104. log = logging.getLogger('base')
  105. log.setLevel(logging.DEBUG)
  106. # log.setLevel(logging.WARNING)
  107. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  108. handler = logging.StreamHandler()
  109. handler.setFormatter(formatter)
  110. log.addHandler(handler)
  111. # ##########################################################################
  112. # ################## Version and VERSION DATE ##############################
  113. # ##########################################################################
  114. version = 8.992
  115. version_date = "2020/02/22"
  116. beta = True
  117. engine = '3D'
  118. # current date now
  119. date = str(datetime.today()).rpartition('.')[0]
  120. date = ''.join(c for c in date if c not in ':-')
  121. date = date.replace(' ', '_')
  122. # URL for update checks and statistics
  123. version_url = "http://flatcam.org/version"
  124. # App URL
  125. app_url = "http://flatcam.org"
  126. # Manual URL
  127. manual_url = "http://flatcam.org/manual/index.html"
  128. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  129. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  130. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  131. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  132. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  133. # this variable will hold the project status
  134. # if True it will mean that the project was modified and not saved
  135. should_we_save = False
  136. # flag is True if saving action has been triggered
  137. save_in_progress = False
  138. # ###########################################################################
  139. # ############################# Signals ################################
  140. # ###########################################################################
  141. # Inform the user
  142. # Handled by:
  143. # * App.info() --> Print on the status bar
  144. inform = QtCore.pyqtSignal(str)
  145. app_quit = QtCore.pyqtSignal()
  146. # General purpose background task
  147. worker_task = QtCore.pyqtSignal(dict)
  148. # File opened
  149. # Handled by:
  150. # * register_folder()
  151. # * register_recent()
  152. # Note: Setting the parameters to unicode does not seem
  153. # to have an effect. Then are received as Qstring
  154. # anyway.
  155. # File type and filename
  156. file_opened = QtCore.pyqtSignal(str, str)
  157. # File type and filename
  158. file_saved = QtCore.pyqtSignal(str, str)
  159. # Percentage of progress
  160. progress = QtCore.pyqtSignal(int)
  161. plots_updated = QtCore.pyqtSignal()
  162. # Emitted by new_object() and passes the new object as argument, plot flag.
  163. # on_object_created() adds the object to the collection, plots on appropriate flag
  164. # and emits new_object_available.
  165. object_created = QtCore.pyqtSignal(object, bool, bool)
  166. # Emitted when a object has been changed (like scaled, mirrored)
  167. object_changed = QtCore.pyqtSignal(object)
  168. # Emitted after object has been plotted.
  169. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  170. object_plotted = QtCore.pyqtSignal(object)
  171. # Emitted when a new object has been added or deleted from/to the collection
  172. object_status_changed = QtCore.pyqtSignal(object, str, str)
  173. message = QtCore.pyqtSignal(str, str, str)
  174. # Emmited when shell command is finished(one command only)
  175. shell_command_finished = QtCore.pyqtSignal(object)
  176. # Emitted when multiprocess pool has been recreated
  177. pool_recreated = QtCore.pyqtSignal(object)
  178. # Emitted when an unhandled exception happens
  179. # in the worker task.
  180. thread_exception = QtCore.pyqtSignal(object)
  181. # used to signal that there are arguments for the app
  182. args_at_startup = QtCore.pyqtSignal(list)
  183. # a reusable signal to replot a list of objects
  184. # should be disconnected after use so it can be reused
  185. replot_signal = pyqtSignal(list)
  186. # signal emitted when jumping
  187. jump_signal = pyqtSignal(tuple)
  188. # signal emitted when jumping
  189. locate_signal = pyqtSignal(tuple, str)
  190. # close app signal
  191. close_app_signal = pyqtSignal()
  192. def __init__(self, user_defaults=True):
  193. """
  194. Starts the application.
  195. :return: app
  196. :rtype: App
  197. """
  198. App.log.info("FlatCAM Starting...")
  199. self.main_thread = QtWidgets.QApplication.instance().thread()
  200. # #########################################################################
  201. # Setup the listening thread for another instance launching with args #####
  202. # #########################################################################
  203. if sys.platform == 'win32' or sys.platform == 'linux':
  204. # make sure the thread is stored by using a self. otherwise it's garbage collected
  205. self.th = QtCore.QThread()
  206. self.th.start(priority=QtCore.QThread.LowestPriority)
  207. self.new_launch = ArgsThread()
  208. self.new_launch.open_signal[list].connect(self.on_startup_args)
  209. self.new_launch.moveToThread(self.th)
  210. self.new_launch.start.emit()
  211. # ############################################################################
  212. # # ################# OS-specific ############################################
  213. # ############################################################################
  214. portable = False
  215. # Folder for user settings.
  216. if sys.platform == 'win32':
  217. from win32comext.shell import shell, shellcon
  218. if platform.architecture()[0] == '32bit':
  219. App.log.debug("Win32!")
  220. else:
  221. App.log.debug("Win64!")
  222. # #########################################################################
  223. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  224. # #########################################################################
  225. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  226. try:
  227. with open(config_file, 'r'):
  228. pass
  229. except FileNotFoundError:
  230. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  231. try:
  232. with open(config_file, 'r') as f:
  233. try:
  234. for line in f:
  235. param = str(line).replace('\n', '').rpartition('=')
  236. if param[0] == 'portable':
  237. try:
  238. portable = eval(param[2])
  239. except NameError:
  240. portable = False
  241. if param[0] == 'headless':
  242. if param[2].lower() == 'true':
  243. self.cmd_line_headless = 1
  244. else:
  245. self.cmd_line_headless = None
  246. except Exception as e:
  247. log.debug('App.__init__() -->%s' % str(e))
  248. return
  249. except FileNotFoundError as e:
  250. log.debug(str(e))
  251. pass
  252. if portable is False:
  253. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  254. else:
  255. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  256. self.os = 'windows'
  257. else: # Linux/Unix/MacOS
  258. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  259. self.os = 'unix'
  260. # ##########################################################################
  261. # ################## Setup folders and files ###############################
  262. # ##########################################################################
  263. if not os.path.exists(self.data_path):
  264. os.makedirs(self.data_path)
  265. App.log.debug('Created data folder: ' + self.data_path)
  266. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  267. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  268. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  269. if not os.path.exists(self.preprocessorpaths):
  270. os.makedirs(self.preprocessorpaths)
  271. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  272. # create geo_tools_db.FlatDB file if there is none
  273. try:
  274. f = open(self.data_path + '/geo_tools_db.FlatDB')
  275. f.close()
  276. except IOError:
  277. App.log.debug('Creating empty geo_tool_db.FlatDB')
  278. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  279. json.dump({}, f)
  280. f.close()
  281. # create fctool_tools_db.FlatDB file if there is none
  282. try:
  283. f = open(self.data_path + '/fctool_tools_db.FlatDB')
  284. f.close()
  285. except IOError:
  286. App.log.debug('Creating empty fctool_tool_db.FlatDB')
  287. f = open(self.data_path + '/fctool_tools_db.FlatDB', 'w')
  288. json.dump({}, f)
  289. f.close()
  290. # create current_defaults.FlatConfig file if there is none
  291. try:
  292. f = open(self.data_path + '/current_defaults.FlatConfig')
  293. f.close()
  294. except IOError:
  295. App.log.debug('Creating empty current_defaults.FlatConfig')
  296. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  297. json.dump({}, f)
  298. f.close()
  299. # create factory_defaults.FlatConfig file if there is none
  300. try:
  301. f = open(self.data_path + '/factory_defaults.FlatConfig')
  302. f.close()
  303. except IOError:
  304. App.log.debug('Creating empty factory_defaults.FlatConfig')
  305. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  306. json.dump({}, f)
  307. f.close()
  308. # create a recent files json file if there is none
  309. try:
  310. f = open(self.data_path + '/recent.json')
  311. f.close()
  312. except IOError:
  313. App.log.debug('Creating empty recent.json')
  314. f = open(self.data_path + '/recent.json', 'w')
  315. json.dump([], f)
  316. f.close()
  317. # create a recent projects json file if there is none
  318. try:
  319. fp = open(self.data_path + '/recent_projects.json')
  320. fp.close()
  321. except IOError:
  322. App.log.debug('Creating empty recent_projects.json')
  323. fp = open(self.data_path + '/recent_projects.json', 'w')
  324. json.dump([], fp)
  325. fp.close()
  326. # Application directory. CHDIR to it. Otherwise, trying to load
  327. # GUI icons will fail as their path is relative.
  328. # This will fail under cx_freeze ...
  329. self.app_home = os.path.dirname(os.path.realpath(__file__))
  330. App.log.debug("Application path is " + self.app_home)
  331. App.log.debug("Started in " + os.getcwd())
  332. # cx_freeze workaround
  333. if os.path.isfile(self.app_home):
  334. self.app_home = os.path.dirname(self.app_home)
  335. os.chdir(self.app_home)
  336. # #################################################################################
  337. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  338. # #################################################################################
  339. self.defaults = LoudDict()
  340. self.defaults.update({
  341. # Global APP Preferences
  342. "decimals_inch": 4,
  343. "decimals_metric": 4,
  344. "version": self.version,
  345. "first_run": True,
  346. "units": "MM",
  347. "global_serial": 0,
  348. "global_stats": dict(),
  349. "global_tabs_detachable": True,
  350. "global_jump_ref": 'abs',
  351. "global_locate_pt": 'bl',
  352. "global_tpdf_tmargin": 15.0,
  353. "global_tpdf_bmargin": 10.0,
  354. "global_tpdf_lmargin": 20.0,
  355. "global_tpdf_rmargin": 20.0,
  356. # General
  357. "global_graphic_engine": '3D',
  358. "global_app_level": 'b',
  359. "global_portable": False,
  360. "global_language": 'English',
  361. "global_version_check": True,
  362. "global_send_stats": True,
  363. "global_pan_button": '2',
  364. "global_mselect_key": 'Control',
  365. "global_project_at_startup": False,
  366. "global_systray_icon": True,
  367. "global_project_autohide": True,
  368. "global_toggle_tooltips": True,
  369. "global_worker_number": 2,
  370. "global_tolerance": 0.005,
  371. "global_open_style": True,
  372. "global_delete_confirmation": True,
  373. "global_compression_level": 3,
  374. "global_save_compressed": True,
  375. "global_machinist_setting": False,
  376. # Global GUI Preferences
  377. "global_gridx": 1.0,
  378. "global_gridy": 1.0,
  379. "global_snap_max": 0.05,
  380. "global_workspace": False,
  381. "global_workspaceT": "A4",
  382. "global_workspace_orientation": 'p',
  383. "global_grid_context_menu": {
  384. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  385. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  386. },
  387. "global_sel_fill": '#a5a5ffbf',
  388. "global_sel_line": '#0000ffbf',
  389. "global_alt_sel_fill": '#BBF268BF',
  390. "global_alt_sel_line": '#006E20BF',
  391. "global_draw_color": '#FF0000',
  392. "global_sel_draw_color": '#0000FF',
  393. "global_proj_item_color": '#000000',
  394. "global_proj_item_dis_color": '#b7b7cb',
  395. "global_activity_icon": 'Ball green',
  396. "global_toolbar_view": 511,
  397. "global_background_timeout": 300000, # Default value is 5 minutes
  398. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  399. # (python trace only for unknown errors),
  400. # 1 = show trace(show trace always),
  401. # 2 = (For the future).
  402. # Persistence
  403. "global_last_folder": None,
  404. "global_last_save_folder": None,
  405. # Default window geometry
  406. "global_def_win_x": 100,
  407. "global_def_win_y": 100,
  408. "global_def_win_w": 1024,
  409. "global_def_win_h": 650,
  410. "global_def_notebook_width": 1,
  411. # Constants...
  412. "global_defaults_save_period_ms": 20000, # Time between default saves.
  413. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  414. "global_shell_at_startup": False, # Show the shell at startup.
  415. "global_recent_limit": 10, # Max. items in recent list.
  416. "global_bookmarks": dict(),
  417. "global_bookmarks_limit": 10,
  418. "fit_key": 'V',
  419. "zoom_out_key": '-',
  420. "zoom_in_key": '=',
  421. "grid_toggle_key": 'G',
  422. "global_zoom_ratio": 1.5,
  423. "global_point_clipboard_format": "(%.*f, %.*f)",
  424. "global_zdownrate": None,
  425. # General GUI Settings
  426. "global_theme": 'white',
  427. "global_gray_icons": False,
  428. "global_hover": False,
  429. "global_selection_shape": True,
  430. "global_layout": "compact",
  431. "global_cursor_type": "small",
  432. "global_cursor_size": 20,
  433. "global_cursor_width": 2,
  434. "global_cursor_color": '#FF0000',
  435. "global_cursor_color_enabled": True,
  436. # Gerber General
  437. "gerber_plot": True,
  438. "gerber_solid": True,
  439. "gerber_multicolored": False,
  440. "gerber_circle_steps": 64,
  441. "gerber_use_buffer_for_union": True,
  442. "gerber_clean_apertures": True,
  443. "gerber_extra_buffering": True,
  444. "gerber_plot_fill": '#BBF268BF',
  445. "gerber_plot_line": '#006E20BF',
  446. "gerber_def_units": 'IN',
  447. "gerber_def_zeros": 'L',
  448. "gerber_save_filters": "Gerber File (*.gbr);;Gerber File (*.bot);;Gerber File (*.bsm);;"
  449. "Gerber File (*.cmp);;Gerber File (*.crc);;Gerber File (*.crs);;"
  450. "Gerber File (*.gb0);;Gerber File (*.gb1);;Gerber File (*.gb2);;"
  451. "Gerber File (*.gb3);;Gerber File (*.gb4);;Gerber File (*.gb5);;"
  452. "Gerber File (*.gb6);;Gerber File (*.gb7);;Gerber File (*.gb8);;"
  453. "Gerber File (*.gb9);;Gerber File (*.gbd);;Gerber File (*.gbl);;"
  454. "Gerber File (*.gbo);;Gerber File (*.gbp);;Gerber File (*.gbs);;"
  455. "Gerber File (*.gdo);;Gerber File (*.ger);;Gerber File (*.gko);;"
  456. "Gerber File (*.gm1);;Gerber File (*.gm2);;Gerber File (*.gm3);;"
  457. "Gerber File (*.grb);;Gerber File (*.gtl);;Gerber File (*.gto);;"
  458. "Gerber File (*.gtp);;Gerber File (*.gts);;Gerber File (*.ly15);;"
  459. "Gerber File (*.ly2);;Gerber File (*.mil);;Gerber File (*.pho);;"
  460. "Gerber File (*.plc);;Gerber File (*.pls);;Gerber File (*.smb);;"
  461. "Gerber File (*.smt);;Gerber File (*.sol);;Gerber File (*.spb);;"
  462. "Gerber File (*.spt);;Gerber File (*.ssb);;Gerber File (*.sst);;"
  463. "Gerber File (*.stc);;Gerber File (*.sts);;Gerber File (*.top);;"
  464. "Gerber File (*.tsm);;Gerber File (*.art)"
  465. "All Files (*.*)",
  466. # Gerber Options
  467. "gerber_isotooldia": 0.1,
  468. "gerber_isopasses": 1,
  469. "gerber_isooverlap": 10,
  470. "gerber_milling_type": "cl",
  471. "gerber_combine_passes": False,
  472. "gerber_iso_scope": 'all',
  473. "gerber_noncoppermargin": 0.1,
  474. "gerber_noncopperrounded": False,
  475. "gerber_bboxmargin": 0.1,
  476. "gerber_bboxrounded": False,
  477. # Gerber Advanced Options
  478. "gerber_aperture_display": False,
  479. "gerber_aperture_scale_factor": 1.0,
  480. "gerber_aperture_buffer_factor": 0.0,
  481. "gerber_follow": False,
  482. "gerber_tool_type": 'circular',
  483. "gerber_vtipdia": 0.1,
  484. "gerber_vtipangle": 30,
  485. "gerber_vcutz": -0.05,
  486. "gerber_iso_type": "full",
  487. "gerber_buffering": "full",
  488. "gerber_simplification": False,
  489. "gerber_simp_tolerance": 0.0005,
  490. # Gerber Export
  491. "gerber_exp_units": 'IN',
  492. "gerber_exp_integer": 2,
  493. "gerber_exp_decimals": 4,
  494. "gerber_exp_zeros": 'L',
  495. # Gerber Editor
  496. "gerber_editor_sel_limit": 30,
  497. "gerber_editor_newcode": 10,
  498. "gerber_editor_newsize": 0.8,
  499. "gerber_editor_newtype": 'C',
  500. "gerber_editor_newdim": "0.5, 0.5",
  501. "gerber_editor_array_size": 5,
  502. "gerber_editor_lin_axis": 'X',
  503. "gerber_editor_lin_pitch": 0.1,
  504. "gerber_editor_lin_angle": 0.0,
  505. "gerber_editor_circ_dir": 'CW',
  506. "gerber_editor_circ_angle": 0.0,
  507. "gerber_editor_scale_f": 1.0,
  508. "gerber_editor_buff_f": 0.1,
  509. "gerber_editor_ma_low": 0.0,
  510. "gerber_editor_ma_high": 1.0,
  511. # Excellon General
  512. "excellon_plot": True,
  513. "excellon_solid": True,
  514. "excellon_format_upper_in": 2,
  515. "excellon_format_lower_in": 4,
  516. "excellon_format_upper_mm": 3,
  517. "excellon_format_lower_mm": 3,
  518. "excellon_zeros": "L",
  519. "excellon_units": "INCH",
  520. "excellon_update": True,
  521. "excellon_optimization_type": 'B',
  522. "excellon_search_time": 3,
  523. "excellon_save_filters": "Excellon File (*.txt);;Excellon File (*.drd);;Excellon File (*.drl);;"
  524. "Excellon File (*.exc);;Excellon File (*.ncd);;Excellon File (*.tap);;"
  525. "Excellon File (*.xln);;All Files (*.*)",
  526. "excellon_plot_fill": '#C40000BF',
  527. "excellon_plot_line": '#750000BF',
  528. # Excellon Options
  529. "excellon_drillz": -1.7,
  530. "excellon_multidepth": False,
  531. "excellon_depthperpass": 0.7,
  532. "excellon_travelz": 2,
  533. "excellon_endz": 0.5,
  534. "excellon_feedrate": 300,
  535. "excellon_spindlespeed": 0,
  536. "excellon_dwell": False,
  537. "excellon_dwelltime": 1,
  538. "excellon_toolchange": False,
  539. "excellon_toolchangez": 15,
  540. "excellon_ppname_e": 'default',
  541. "excellon_tooldia": 0.8,
  542. "excellon_slot_tooldia": 1.8,
  543. "excellon_gcode_type": "drills",
  544. # Excellon Advanced Options
  545. "excellon_offset": 0.0,
  546. "excellon_toolchangexy": "0.0, 0.0",
  547. "excellon_startz": None,
  548. "excellon_feedrate_rapid": 1500,
  549. "excellon_z_pdepth": -0.02,
  550. "excellon_feedrate_probe": 75,
  551. "excellon_spindledir": 'CW',
  552. "excellon_f_plunge": False,
  553. "excellon_f_retract": False,
  554. # Excellon Export
  555. "excellon_exp_units": 'INCH',
  556. "excellon_exp_format": 'ndec',
  557. "excellon_exp_integer": 2,
  558. "excellon_exp_decimals": 4,
  559. "excellon_exp_zeros": 'LZ',
  560. "excellon_exp_slot_type": 'routing',
  561. # Excellon Editor
  562. "excellon_editor_sel_limit": 30,
  563. "excellon_editor_newdia": 1.0,
  564. "excellon_editor_array_size": 5,
  565. "excellon_editor_lin_dir": 'X',
  566. "excellon_editor_lin_pitch": 2.54,
  567. "excellon_editor_lin_angle": 0.0,
  568. "excellon_editor_circ_dir": 'CW',
  569. "excellon_editor_circ_angle": 12,
  570. # Excellon Slots
  571. "excellon_editor_slot_direction": 'X',
  572. "excellon_editor_slot_angle": 0.0,
  573. "excellon_editor_slot_length": 5.0,
  574. # Excellon Slot Array
  575. "excellon_editor_slot_array_size": 5,
  576. "excellon_editor_slot_lin_dir": 'X',
  577. "excellon_editor_slot_lin_pitch": 2.54,
  578. "excellon_editor_slot_lin_angle": 0.0,
  579. "excellon_editor_slot_circ_dir": 'CW',
  580. "excellon_editor_slot_circ_angle": 0.0,
  581. # Geometry General
  582. "geometry_plot": True,
  583. "geometry_circle_steps": 64,
  584. "geometry_cnctooldia": "2.4",
  585. "geometry_plot_line": "#FF0000",
  586. # Geometry Options
  587. "geometry_cutz": -2.4,
  588. "geometry_vtipdia": 0.1,
  589. "geometry_vtipangle": 30,
  590. "geometry_multidepth": False,
  591. "geometry_depthperpass": 0.8,
  592. "geometry_travelz": 2,
  593. "geometry_toolchange": False,
  594. "geometry_toolchangez": 15.0,
  595. "geometry_endz": 15.0,
  596. "geometry_feedrate": 120,
  597. "geometry_feedrate_z": 60,
  598. "geometry_spindlespeed": 0,
  599. "geometry_dwell": False,
  600. "geometry_dwelltime": 1,
  601. "geometry_ppname_g": 'default',
  602. # Geometry Advanced Options
  603. "geometry_toolchangexy": "0.0, 0.0",
  604. "geometry_startz": None,
  605. "geometry_feedrate_rapid": 1500,
  606. "geometry_extracut": False,
  607. "geometry_extracut_length": 0.1,
  608. "geometry_z_pdepth": -0.02,
  609. "geometry_f_plunge": False,
  610. "geometry_spindledir": 'CW',
  611. "geometry_feedrate_probe": 75,
  612. "geometry_segx": 0.0,
  613. "geometry_segy": 0.0,
  614. # Geometry Editor
  615. "geometry_editor_sel_limit": 30,
  616. "geometry_editor_milling_type": "cl",
  617. # CNC Job General
  618. "cncjob_plot": True,
  619. "cncjob_plot_kind": 'all',
  620. "cncjob_annotation": True,
  621. "cncjob_tooldia": 1.0,
  622. "cncjob_coords_type": "G90",
  623. "cncjob_coords_decimals": 4,
  624. "cncjob_fr_decimals": 2,
  625. "cncjob_steps_per_circle": 64,
  626. "cncjob_footer": False,
  627. "cncjob_line_ending": False,
  628. "cncjob_save_filters": "G-Code Files (*.nc);;G-Code Files (*.din);;G-Code Files (*.dnc);;"
  629. "G-Code Files (*.ecs);;G-Code Files (*.eia);;G-Code Files (*.fan);;"
  630. "G-Code Files (*.fgc);;G-Code Files (*.fnc);;G-Code Files (*.gc);;"
  631. "G-Code Files (*.gcd);;G-Code Files (*.gcode);;G-Code Files (*.h);;"
  632. "G-Code Files (*.hnc);;G-Code Files (*.i);;G-Code Files (*.min);;"
  633. "G-Code Files (*.mpf);;G-Code Files (*.mpr);;G-Code Files (*.cnc);;"
  634. "G-Code Files (*.ncc);;G-Code Files (*.ncg);;G-Code Files (*.ncp);;"
  635. "G-Code Files (*.ngc);;G-Code Files (*.out);;G-Code Files (*.ply);;"
  636. "G-Code Files (*.sbp);;G-Code Files (*.tap);;G-Code Files (*.xpi);;"
  637. "All Files (*.*)",
  638. "cncjob_plot_line": '#4650BDFF',
  639. "cncjob_plot_fill": '#5E6CFFFF',
  640. "cncjob_travel_line": '#B5AB3A4C',
  641. "cncjob_travel_fill": '#F0E24D4C',
  642. # CNC Job Options
  643. "cncjob_prepend": "",
  644. "cncjob_append": "",
  645. # CNC Job Advanced Options
  646. "cncjob_toolchange_macro": "",
  647. "cncjob_toolchange_macro_enable": False,
  648. "cncjob_annotation_fontsize": 9,
  649. "cncjob_annotation_fontcolor": '#990000',
  650. # NCC Tool
  651. "tools_ncctools": "1.0, 0.5",
  652. "tools_nccorder": 'rev',
  653. "tools_nccoverlap": 40,
  654. "tools_nccmargin": 1.0,
  655. "tools_nccmethod": "seed",
  656. "tools_nccconnect": True,
  657. "tools_ncccontour": True,
  658. "tools_nccrest": False,
  659. "tools_ncc_offset_choice": False,
  660. "tools_ncc_offset_value": 0.0000,
  661. "tools_nccref": 'itself',
  662. "tools_ncc_plotting": 'normal',
  663. "tools_nccmilling_type": 'cl',
  664. "tools_ncctool_type": 'C1',
  665. "tools_ncccutz": -0.05,
  666. "tools_ncctipdia": 0.1,
  667. "tools_ncctipangle": 30,
  668. "tools_nccnewdia": 0.1,
  669. # Cutout Tool
  670. "tools_cutouttooldia": 2.4,
  671. "tools_cutoutkind": "single",
  672. "tools_cutoutmargin": 0.1,
  673. "tools_cutout_z": -1.8,
  674. "tools_cutout_depthperpass": 0.6,
  675. "tools_cutout_mdepth": True,
  676. "tools_cutoutgapsize": 4,
  677. "tools_gaps_ff": "4",
  678. "tools_cutout_convexshape": False,
  679. # Paint Tool
  680. "tools_painttooldia": 0.3,
  681. "tools_paintorder": 'rev',
  682. "tools_paintoverlap": 20,
  683. "tools_paintmargin": 0.0,
  684. "tools_paintmethod": "seed",
  685. "tools_selectmethod": "all",
  686. "tools_pathconnect": True,
  687. "tools_paintcontour": True,
  688. "tools_paint_plotting": 'normal',
  689. "tools_paintrest": False,
  690. "tools_painttool_type": 'C1',
  691. "tools_paintcutz": -0.05,
  692. "tools_painttipdia": 0.1,
  693. "tools_painttipangle": 30,
  694. "tools_paintnewdia": 0.1,
  695. # 2-Sided Tool
  696. "tools_2sided_mirror_axis": "X",
  697. "tools_2sided_axis_loc": "point",
  698. "tools_2sided_drilldia": 3.125,
  699. "tools_2sided_allign_axis": "X",
  700. # Film Tool
  701. "tools_film_type": 'neg',
  702. "tools_film_boundary": 1.0,
  703. "tools_film_scale_stroke": 0,
  704. "tools_film_color": '#000000',
  705. "tools_film_scale_cb": False,
  706. "tools_film_scale_x_entry": 1.0,
  707. "tools_film_scale_y_entry": 1.0,
  708. "tools_film_skew_cb": False,
  709. "tools_film_skew_x_entry": 0.0,
  710. "tools_film_skew_y_entry": 0.0,
  711. "tools_film_skew_ref_radio": 'bottomleft',
  712. "tools_film_mirror_cb": False,
  713. "tools_film_mirror_axis_radio": 'none',
  714. "tools_film_file_type_radio": 'svg',
  715. "tools_film_orientation": 'p',
  716. "tools_film_pagesize": 'A4',
  717. # Panel Tool
  718. "tools_panelize_spacing_columns": 0,
  719. "tools_panelize_spacing_rows": 0,
  720. "tools_panelize_columns": 1,
  721. "tools_panelize_rows": 1,
  722. "tools_panelize_constrain": False,
  723. "tools_panelize_constrainx": 200.0,
  724. "tools_panelize_constrainy": 290.0,
  725. "tools_panelize_panel_type": 'gerber',
  726. # Calculators Tool
  727. "tools_calc_vshape_tip_dia": 0.2,
  728. "tools_calc_vshape_tip_angle": 30,
  729. "tools_calc_vshape_cut_z": 0.05,
  730. "tools_calc_electro_length": 10.0,
  731. "tools_calc_electro_width": 10.0,
  732. "tools_calc_electro_cdensity": 13.0,
  733. "tools_calc_electro_growth": 10.0,
  734. # Transform Tool
  735. "tools_transform_rotate": 90,
  736. "tools_transform_skew_x": 0.0,
  737. "tools_transform_skew_y": 0.0,
  738. "tools_transform_scale_x": 1.0,
  739. "tools_transform_scale_y": 1.0,
  740. "tools_transform_scale_link": True,
  741. "tools_transform_scale_reference": True,
  742. "tools_transform_offset_x": 0.0,
  743. "tools_transform_offset_y": 0.0,
  744. "tools_transform_mirror_reference": False,
  745. "tools_transform_mirror_point": (0, 0),
  746. "tools_transform_buffer_dis": 0.0,
  747. "tools_transform_buffer_factor": 100.0,
  748. "tools_transform_buffer_corner": True,
  749. # SolderPaste Tool
  750. "tools_solderpaste_tools": "1.0, 0.3",
  751. "tools_solderpaste_new": 0.3,
  752. "tools_solderpaste_z_start": 0.05,
  753. "tools_solderpaste_z_dispense": 0.1,
  754. "tools_solderpaste_z_stop": 0.05,
  755. "tools_solderpaste_z_travel": 0.1,
  756. "tools_solderpaste_z_toolchange": 1.0,
  757. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  758. "tools_solderpaste_frxy": 150,
  759. "tools_solderpaste_frz": 150,
  760. "tools_solderpaste_frz_dispense": 1.0,
  761. "tools_solderpaste_speedfwd": 300,
  762. "tools_solderpaste_dwellfwd": 1,
  763. "tools_solderpaste_speedrev": 200,
  764. "tools_solderpaste_dwellrev": 1,
  765. "tools_solderpaste_pp": 'Paste_1',
  766. # Subtract Tool
  767. "tools_sub_close_paths": True,
  768. # Distance Tool
  769. "tools_dist_snap_center": False,
  770. # ###################################################################################
  771. # ################################ TOOLS 2 ##########################################
  772. # ###################################################################################
  773. # Optimal Tool
  774. "tools_opt_precision": 4,
  775. # Check Rules Tool
  776. "tools_cr_trace_size": True,
  777. "tools_cr_trace_size_val": 0.25,
  778. "tools_cr_c2c": True,
  779. "tools_cr_c2c_val": 0.25,
  780. "tools_cr_c2o": True,
  781. "tools_cr_c2o_val": 1.0,
  782. "tools_cr_s2s": True,
  783. "tools_cr_s2s_val": 0.25,
  784. "tools_cr_s2sm": True,
  785. "tools_cr_s2sm_val": 0.25,
  786. "tools_cr_s2o": True,
  787. "tools_cr_s2o_val": 1.0,
  788. "tools_cr_sm2sm": True,
  789. "tools_cr_sm2sm_val": 0.25,
  790. "tools_cr_ri": True,
  791. "tools_cr_ri_val": 0.3,
  792. "tools_cr_h2h": True,
  793. "tools_cr_h2h_val": 0.3,
  794. "tools_cr_dh": True,
  795. "tools_cr_dh_val": 0.3,
  796. # QRCode Tool
  797. "tools_qrcode_version": 1,
  798. "tools_qrcode_error": 'L',
  799. "tools_qrcode_box_size": 3,
  800. "tools_qrcode_border_size": 4,
  801. "tools_qrcode_qrdata": '',
  802. "tools_qrcode_polarity": 'pos',
  803. "tools_qrcode_rounded": 's',
  804. "tools_qrcode_fill_color": '#000000',
  805. "tools_qrcode_back_color": '#FFFFFF',
  806. "tools_qrcode_sel_limit": 330,
  807. # Copper Thieving Tool
  808. "tools_copper_thieving_clearance": 0.25,
  809. "tools_copper_thieving_margin": 1.0,
  810. "tools_copper_thieving_reference": 'itself',
  811. "tools_copper_thieving_box_type": 'rect',
  812. "tools_copper_thieving_circle_steps": 64,
  813. "tools_copper_thieving_fill_type": 'solid',
  814. "tools_copper_thieving_dots_dia": 1.0,
  815. "tools_copper_thieving_dots_spacing": 2.0,
  816. "tools_copper_thieving_squares_size": 1.0,
  817. "tools_copper_thieving_squares_spacing": 2.0,
  818. "tools_copper_thieving_lines_size": 0.25,
  819. "tools_copper_thieving_lines_spacing": 2.0,
  820. "tools_copper_thieving_rb_margin": 1.0,
  821. "tools_copper_thieving_rb_thickness": 1.0,
  822. "tools_copper_thieving_mask_clearance": 0.0,
  823. # Fiducials Tool
  824. "tools_fiducials_dia": 1.0,
  825. "tools_fiducials_margin": 1.0,
  826. "tools_fiducials_mode": 'auto',
  827. "tools_fiducials_second_pos": 'up',
  828. "tools_fiducials_type": 'circular',
  829. "tools_fiducials_line_thickness": 0.25,
  830. # Calibration Tool
  831. "tools_cal_calsource": 'object',
  832. "tools_cal_travelz": 2.0,
  833. "tools_cal_verz": 0.1,
  834. "tools_cal_zeroz": False,
  835. "tools_cal_toolchangez": 15,
  836. "tools_cal_toolchange_xy": '',
  837. "tools_cal_sec_point": 'tl',
  838. # Drills Extraction Tool
  839. "tools_edrills_hole_type": 'fixed',
  840. "tools_edrills_hole_fixed_dia": 0.5,
  841. "tools_edrills_hole_prop_factor": 80.0,
  842. "tools_edrills_circular_ring": 0.2,
  843. "tools_edrills_oblong_ring": 0.2,
  844. "tools_edrills_square_ring": 0.2,
  845. "tools_edrills_rectangular_ring": 0.2,
  846. "tools_edrills_others_ring": 0.2,
  847. "tools_edrills_circular": True,
  848. "tools_edrills_oblong": False,
  849. "tools_edrills_square": False,
  850. "tools_edrills_rectangular": False,
  851. "tools_edrills_others": False,
  852. # Punch Gerber Tool
  853. "tools_punch_hole_type": 'exc',
  854. "tools_punch_hole_fixed_dia": 0.5,
  855. "tools_punch_hole_prop_factor": 80.0,
  856. "tools_punch_circular_ring": 0.2,
  857. "tools_punch_oblong_ring": 0.2,
  858. "tools_punch_square_ring": 0.2,
  859. "tools_punch_rectangular_ring": 0.2,
  860. "tools_punch_others_ring": 0.2,
  861. "tools_punch_circular": True,
  862. "tools_punch_oblong": False,
  863. "tools_punch_square": True,
  864. "tools_punch_rectangular": False,
  865. "tools_punch_others": False,
  866. # Align Objects Tool
  867. "tools_align_objects_align_type": 'sp',
  868. # Utilities
  869. # file associations
  870. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  871. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  872. 'ncg, ncp, ngc, out, ply, rol, sbp, tap, xpi',
  873. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, gb0, gb1, gb2, gb3, gb4, gb5, gb6, gb7, gb8, gb9, gbd, '
  874. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  875. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  876. # Keyword list
  877. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  878. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  879. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  880. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  881. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwelltime, '
  882. 'extracut_length, '
  883. 'feedrate_z, grbl_11, GRBL_laser, gridoffsety, gridx, gridy, has_offset, '
  884. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  885. 'minoffset, name, offset, opt_type, order, outname, overlap, '
  886. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  887. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  888. 'toolchange_xy, toolchangez, '
  889. 'tooldia, use_threads, value, x, x0, x1, y, y0, y1, z_cut, '
  890. 'z_move',
  891. "script_autocompleter": True,
  892. "script_text": "",
  893. "script_plot": True,
  894. "script_source_file": "",
  895. "document_autocompleter": False,
  896. "document_text": "",
  897. "document_plot": True,
  898. "document_source_file": "",
  899. "document_font_color": '#000000',
  900. "document_sel_color": '#0055ff',
  901. "document_font_size": 6,
  902. "document_tab_size": 80,
  903. })
  904. # ############################################################
  905. # ############### Load defaults from file ####################
  906. # ############################################################
  907. self.old_defaults_found = False
  908. if user_defaults:
  909. self.load_defaults(filename='current_defaults')
  910. if self.defaults['units'] == 'MM':
  911. self.decimals = int(self.defaults['decimals_metric'])
  912. else:
  913. self.decimals = int(self.defaults['decimals_inch'])
  914. if self.defaults["global_gray_icons"] is False:
  915. self.resource_location = 'share'
  916. else:
  917. self.resource_location = 'share/dark_resources'
  918. self.current_units = self.defaults['units']
  919. # store here the current self.defaults so it can be restored if Preferences changes are cancelled
  920. self.current_defaults = dict()
  921. self.current_defaults.update(self.defaults)
  922. # ##########################################################################
  923. # ##################### SETUP OBJECT CLASSES ###############################
  924. # ##########################################################################
  925. self.setup_obj_classes()
  926. # ##########################################################################
  927. # ##################### CREATE MULTIPROCESSING POOL ########################
  928. # ##########################################################################
  929. self.pool = Pool()
  930. # ##########################################################################
  931. # ################## Setting the Splash Screen #############################
  932. # ##########################################################################
  933. splash_settings = QSettings("Open Source", "FlatCAM")
  934. if splash_settings.contains("splash_screen"):
  935. show_splash = splash_settings.value("splash_screen")
  936. else:
  937. splash_settings.setValue('splash_screen', 1)
  938. # This will write the setting to the platform specific storage.
  939. del splash_settings
  940. show_splash = 1
  941. if show_splash and self.cmd_line_headless != 1:
  942. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  943. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  944. # self.splash.setMask(splash_pix.mask())
  945. # move splashscreen to the current monitor
  946. desktop = QtWidgets.QApplication.desktop()
  947. screen = desktop.screenNumber(QtGui.QCursor.pos())
  948. current_screen_center = desktop.availableGeometry(screen).center()
  949. self.splash.move(current_screen_center - self.splash.rect().center())
  950. self.splash.show()
  951. self.splash.showMessage(_("FlatCAM is initializing ..."),
  952. alignment=Qt.AlignBottom | Qt.AlignLeft,
  953. color=QtGui.QColor("gray"))
  954. else:
  955. show_splash = 0
  956. # #############################################################################
  957. # ##################### Initialize GUI ########################################
  958. # #############################################################################
  959. # FlatCAM colors used in plotting
  960. self.FC_light_green = '#BBF268BF'
  961. self.FC_dark_green = '#006E20BF'
  962. self.FC_light_blue = '#a5a5ffbf'
  963. self.FC_dark_blue = '#0000ffbf'
  964. QtCore.QObject.__init__(self)
  965. self.ui = FlatCAMGUI(self)
  966. self.on_grid_snap_triggered(state=True)
  967. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  968. if theme_settings.contains("theme"):
  969. theme = theme_settings.value('theme', type=str)
  970. else:
  971. theme = 'white'
  972. if self.defaults["global_cursor_color_enabled"]:
  973. self.cursor_color_3D = self.defaults["global_cursor_color"]
  974. else:
  975. if theme == 'white':
  976. self.cursor_color_3D = 'black'
  977. else:
  978. self.cursor_color_3D = 'gray'
  979. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  980. self.ui.final_save.connect(self.final_save)
  981. # restore the toolbar view
  982. self.restore_toolbar_view()
  983. # restore the GUI geometry
  984. self.restore_main_win_geom()
  985. # set FlatCAM units in the Status bar
  986. self.set_screen_units(self.defaults['units'])
  987. # #############################################################################
  988. # ######################## UPDATE PREFERENCES GUI FORMS #######################
  989. # #############################################################################
  990. # when adding entries here read the comments in the method found bellow named:
  991. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  992. self.defaults_form_fields = {
  993. # General App
  994. "decimals_inch": self.ui.general_defaults_form.general_app_group.precision_inch_entry,
  995. "decimals_metric": self.ui.general_defaults_form.general_app_group.precision_metric_entry,
  996. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  997. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  998. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  999. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  1000. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  1001. "global_systray_icon": self.ui.general_defaults_form.general_app_group.systray_cb,
  1002. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  1003. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  1004. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  1005. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  1006. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  1007. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  1008. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_spinner,
  1009. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  1010. "global_tpdf_tmargin": self.ui.general_defaults_form.general_app_group.tmargin_entry,
  1011. "global_tpdf_bmargin": self.ui.general_defaults_form.general_app_group.bmargin_entry,
  1012. "global_tpdf_lmargin": self.ui.general_defaults_form.general_app_group.lmargin_entry,
  1013. "global_tpdf_rmargin": self.ui.general_defaults_form.general_app_group.rmargin_entry,
  1014. # General GUI Preferences
  1015. "global_theme": self.ui.general_defaults_form.general_gui_group.theme_radio,
  1016. "global_gray_icons": self.ui.general_defaults_form.general_gui_group.gray_icons_cb,
  1017. "global_layout": self.ui.general_defaults_form.general_gui_group.layout_combo,
  1018. "global_hover": self.ui.general_defaults_form.general_gui_group.hover_cb,
  1019. "global_selection_shape": self.ui.general_defaults_form.general_gui_group.selection_cb,
  1020. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  1021. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  1022. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  1023. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  1024. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  1025. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  1026. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  1027. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  1028. "global_project_autohide": self.ui.general_defaults_form.general_gui_group.project_autohide_cb,
  1029. # General GUI Settings
  1030. "global_gridx": self.ui.general_defaults_form.general_app_set_group.gridx_entry,
  1031. "global_gridy": self.ui.general_defaults_form.general_app_set_group.gridy_entry,
  1032. "global_snap_max": self.ui.general_defaults_form.general_app_set_group.snap_max_dist_entry,
  1033. "global_workspace": self.ui.general_defaults_form.general_app_set_group.workspace_cb,
  1034. "global_workspaceT": self.ui.general_defaults_form.general_app_set_group.wk_cb,
  1035. "global_workspace_orientation": self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio,
  1036. "global_cursor_type": self.ui.general_defaults_form.general_app_set_group.cursor_radio,
  1037. "global_cursor_size": self.ui.general_defaults_form.general_app_set_group.cursor_size_entry,
  1038. "global_cursor_width": self.ui.general_defaults_form.general_app_set_group.cursor_width_entry,
  1039. "global_cursor_color_enabled": self.ui.general_defaults_form.general_app_set_group.mouse_cursor_color_cb,
  1040. "global_cursor_color": self.ui.general_defaults_form.general_app_set_group.mouse_cursor_entry,
  1041. "global_pan_button": self.ui.general_defaults_form.general_app_set_group.pan_button_radio,
  1042. "global_mselect_key": self.ui.general_defaults_form.general_app_set_group.mselect_radio,
  1043. "global_delete_confirmation": self.ui.general_defaults_form.general_app_set_group.delete_conf_cb,
  1044. "global_open_style": self.ui.general_defaults_form.general_app_set_group.open_style_cb,
  1045. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_set_group.toggle_tooltips_cb,
  1046. "global_machinist_setting": self.ui.general_defaults_form.general_app_set_group.machinist_cb,
  1047. "global_bookmarks_limit": self.ui.general_defaults_form.general_app_set_group.bm_limit_spinner,
  1048. "global_activity_icon": self.ui.general_defaults_form.general_app_set_group.activity_combo,
  1049. # Gerber General
  1050. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  1051. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  1052. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  1053. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  1054. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  1055. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  1056. "gerber_clean_apertures": self.ui.gerber_defaults_form.gerber_gen_group.gerber_clean_cb,
  1057. "gerber_extra_buffering": self.ui.gerber_defaults_form.gerber_gen_group.gerber_extra_buffering,
  1058. "gerber_plot_fill": self.ui.gerber_defaults_form.gerber_gen_group.pf_color_entry,
  1059. "gerber_plot_line": self.ui.gerber_defaults_form.gerber_gen_group.pl_color_entry,
  1060. # Gerber Options
  1061. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  1062. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  1063. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  1064. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  1065. "gerber_iso_scope": self.ui.gerber_defaults_form.gerber_opt_group.iso_scope_radio,
  1066. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  1067. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  1068. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  1069. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  1070. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  1071. # Gerber Advanced Options
  1072. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  1073. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  1074. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  1075. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  1076. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  1077. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  1078. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  1079. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  1080. "gerber_iso_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.iso_type_radio,
  1081. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  1082. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  1083. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  1084. # Gerber Export
  1085. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  1086. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  1087. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  1088. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  1089. # Gerber Editor
  1090. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  1091. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  1092. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  1093. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  1094. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  1095. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  1096. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  1097. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  1098. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  1099. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  1100. "gerber_editor_circ_angle":
  1101. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  1102. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  1103. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  1104. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  1105. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  1106. # Excellon General
  1107. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  1108. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  1109. "excellon_format_upper_in":
  1110. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  1111. "excellon_format_lower_in":
  1112. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  1113. "excellon_format_upper_mm":
  1114. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1115. "excellon_format_lower_mm":
  1116. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1117. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  1118. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  1119. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  1120. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  1121. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  1122. "excellon_plot_fill": self.ui.excellon_defaults_form.excellon_gen_group.fill_color_entry,
  1123. "excellon_plot_line": self.ui.excellon_defaults_form.excellon_gen_group.line_color_entry,
  1124. # Excellon Options
  1125. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  1126. "excellon_multidepth": self.ui.excellon_defaults_form.excellon_opt_group.mpass_cb,
  1127. "excellon_depthperpass":self.ui.excellon_defaults_form.excellon_opt_group.maxdepth_entry,
  1128. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  1129. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.endz_entry,
  1130. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_z_entry,
  1131. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  1132. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  1133. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  1134. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  1135. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  1136. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  1137. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  1138. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  1139. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  1140. # Excellon Advanced Options
  1141. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  1142. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  1143. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  1144. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1145. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  1146. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  1147. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  1148. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  1149. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  1150. # Excellon Export
  1151. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  1152. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  1153. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  1154. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  1155. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  1156. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  1157. # Excellon Editor
  1158. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  1159. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  1160. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  1161. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  1162. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  1163. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  1164. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  1165. "excellon_editor_circ_angle":
  1166. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  1167. # Excellon Slots
  1168. "excellon_editor_slot_direction":
  1169. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  1170. "excellon_editor_slot_angle":
  1171. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  1172. "excellon_editor_slot_length":
  1173. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  1174. # Excellon Slots
  1175. "excellon_editor_slot_array_size":
  1176. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  1177. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  1178. "excellon_editor_slot_lin_pitch":
  1179. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  1180. "excellon_editor_slot_lin_angle":
  1181. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  1182. "excellon_editor_slot_circ_dir":
  1183. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  1184. "excellon_editor_slot_circ_angle":
  1185. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  1186. # Geometry General
  1187. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  1188. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  1189. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  1190. "geometry_plot_line": self.ui.geometry_defaults_form.geometry_gen_group.line_color_entry,
  1191. # Geometry Options
  1192. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  1193. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  1194. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  1195. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.feedrate_z_entry,
  1196. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  1197. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  1198. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  1199. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  1200. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  1201. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  1202. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.endz_entry,
  1203. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  1204. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  1205. # Geometry Advanced Options
  1206. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  1207. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  1208. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_rapid_entry,
  1209. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  1210. "geometry_extracut_length": self.ui.geometry_defaults_form.geometry_adv_opt_group.e_cut_entry,
  1211. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  1212. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  1213. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  1214. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  1215. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  1216. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  1217. # Geometry Editor
  1218. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  1219. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  1220. # CNCJob General
  1221. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  1222. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  1223. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  1224. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  1225. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  1226. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  1227. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  1228. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  1229. "cncjob_line_ending": self.ui.cncjob_defaults_form.cncjob_gen_group.line_ending_cb,
  1230. "cncjob_plot_line": self.ui.cncjob_defaults_form.cncjob_gen_group.line_color_entry,
  1231. "cncjob_plot_fill": self.ui.cncjob_defaults_form.cncjob_gen_group.fill_color_entry,
  1232. "cncjob_travel_line": self.ui.cncjob_defaults_form.cncjob_gen_group.tline_color_entry,
  1233. "cncjob_travel_fill": self.ui.cncjob_defaults_form.cncjob_gen_group.tfill_color_entry,
  1234. # CNC Job Options
  1235. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  1236. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  1237. # CNC Job Advanced Options
  1238. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  1239. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  1240. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  1241. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  1242. # NCC Tool
  1243. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  1244. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  1245. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  1246. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  1247. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  1248. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  1249. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  1250. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  1251. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  1252. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  1253. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  1254. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  1255. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  1256. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  1257. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  1258. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  1259. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  1260. "tools_nccnewdia": self.ui.tools_defaults_form.tools_ncc_group.newdia_entry,
  1261. # CutOut Tool
  1262. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  1263. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  1264. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  1265. "tools_cutout_z": self.ui.tools_defaults_form.tools_cutout_group.cutz_entry,
  1266. "tools_cutout_depthperpass": self.ui.tools_defaults_form.tools_cutout_group.maxdepth_entry,
  1267. "tools_cutout_mdepth": self.ui.tools_defaults_form.tools_cutout_group.mpass_cb,
  1268. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  1269. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  1270. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  1271. # Paint Area Tool
  1272. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  1273. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  1274. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  1275. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  1276. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  1277. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  1278. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  1279. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  1280. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  1281. "tools_paintrest": self.ui.tools_defaults_form.tools_paint_group.rest_cb,
  1282. "tools_painttool_type": self.ui.tools_defaults_form.tools_paint_group.tool_type_radio,
  1283. "tools_paintcutz": self.ui.tools_defaults_form.tools_paint_group.cutz_entry,
  1284. "tools_painttipdia": self.ui.tools_defaults_form.tools_paint_group.tipdia_entry,
  1285. "tools_painttipangle": self.ui.tools_defaults_form.tools_paint_group.tipangle_entry,
  1286. "tools_paintnewdia": self.ui.tools_defaults_form.tools_paint_group.newdia_entry,
  1287. # 2-sided Tool
  1288. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  1289. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  1290. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  1291. "tools_2sided_allign_axis": self.ui.tools_defaults_form.tools_2sided_group.align_axis_radio,
  1292. # Film Tool
  1293. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  1294. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  1295. "tools_film_scale_stroke": self.ui.tools_defaults_form.tools_film_group.film_scale_stroke_entry,
  1296. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  1297. "tools_film_scale_cb": self.ui.tools_defaults_form.tools_film_group.film_scale_cb,
  1298. "tools_film_scale_x_entry": self.ui.tools_defaults_form.tools_film_group.film_scalex_entry,
  1299. "tools_film_scale_y_entry": self.ui.tools_defaults_form.tools_film_group.film_scaley_entry,
  1300. "tools_film_skew_cb": self.ui.tools_defaults_form.tools_film_group.film_skew_cb,
  1301. "tools_film_skew_x_entry": self.ui.tools_defaults_form.tools_film_group.film_skewx_entry,
  1302. "tools_film_skew_y_entry": self.ui.tools_defaults_form.tools_film_group.film_skewy_entry,
  1303. "tools_film_skew_ref_radio": self.ui.tools_defaults_form.tools_film_group.film_skew_reference,
  1304. "tools_film_mirror_cb": self.ui.tools_defaults_form.tools_film_group.film_mirror_cb,
  1305. "tools_film_mirror_axis_radio": self.ui.tools_defaults_form.tools_film_group.film_mirror_axis,
  1306. "tools_film_file_type_radio": self.ui.tools_defaults_form.tools_film_group.file_type_radio,
  1307. "tools_film_orientation": self.ui.tools_defaults_form.tools_film_group.orientation_radio,
  1308. "tools_film_pagesize": self.ui.tools_defaults_form.tools_film_group.pagesize_combo,
  1309. # Panelize Tool
  1310. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  1311. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  1312. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  1313. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  1314. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  1315. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  1316. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  1317. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  1318. # Calculators Tool
  1319. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  1320. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  1321. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  1322. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  1323. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  1324. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  1325. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  1326. # Transformations Tool
  1327. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  1328. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  1329. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  1330. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  1331. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  1332. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  1333. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  1334. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  1335. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  1336. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  1337. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  1338. "tools_transform_buffer_dis": self.ui.tools_defaults_form.tools_transform_group.buffer_entry,
  1339. "tools_transform_buffer_factor": self.ui.tools_defaults_form.tools_transform_group.buffer_factor_entry,
  1340. "tools_transform_buffer_corner": self.ui.tools_defaults_form.tools_transform_group.buffer_rounded_cb,
  1341. # SolderPaste Dispensing Tool
  1342. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  1343. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  1344. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  1345. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  1346. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  1347. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  1348. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  1349. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  1350. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  1351. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  1352. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  1353. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  1354. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  1355. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  1356. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  1357. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  1358. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  1359. # ###################################################################################
  1360. # ################################ TOOLS 2 ##########################################
  1361. # ###################################################################################
  1362. # Optimal Tool
  1363. "tools_opt_precision": self.ui.tools2_defaults_form.tools2_optimal_group.precision_sp,
  1364. # Check Rules Tool
  1365. "tools_cr_trace_size": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_cb,
  1366. "tools_cr_trace_size_val": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_entry,
  1367. "tools_cr_c2c": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_cb,
  1368. "tools_cr_c2c_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_entry,
  1369. "tools_cr_c2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_cb,
  1370. "tools_cr_c2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_entry,
  1371. "tools_cr_s2s": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_cb,
  1372. "tools_cr_s2s_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_entry,
  1373. "tools_cr_s2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_cb,
  1374. "tools_cr_s2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_entry,
  1375. "tools_cr_s2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_cb,
  1376. "tools_cr_s2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_entry,
  1377. "tools_cr_sm2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_cb,
  1378. "tools_cr_sm2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_entry,
  1379. "tools_cr_ri": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_cb,
  1380. "tools_cr_ri_val": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_entry,
  1381. "tools_cr_h2h": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_cb,
  1382. "tools_cr_h2h_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_entry,
  1383. "tools_cr_dh": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_cb,
  1384. "tools_cr_dh_val": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_entry,
  1385. # QRCode Tool
  1386. "tools_qrcode_version": self.ui.tools2_defaults_form.tools2_qrcode_group.version_entry,
  1387. "tools_qrcode_error": self.ui.tools2_defaults_form.tools2_qrcode_group.error_radio,
  1388. "tools_qrcode_box_size": self.ui.tools2_defaults_form.tools2_qrcode_group.bsize_entry,
  1389. "tools_qrcode_border_size": self.ui.tools2_defaults_form.tools2_qrcode_group.border_size_entry,
  1390. "tools_qrcode_qrdata": self.ui.tools2_defaults_form.tools2_qrcode_group.text_data,
  1391. "tools_qrcode_polarity": self.ui.tools2_defaults_form.tools2_qrcode_group.pol_radio,
  1392. "tools_qrcode_rounded": self.ui.tools2_defaults_form.tools2_qrcode_group.bb_radio,
  1393. "tools_qrcode_fill_color": self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry,
  1394. "tools_qrcode_back_color": self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry,
  1395. "tools_qrcode_sel_limit": self.ui.tools2_defaults_form.tools2_qrcode_group.sel_limit_entry,
  1396. # Copper Thieving Tool
  1397. "tools_copper_thieving_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_entry,
  1398. "tools_copper_thieving_margin": self.ui.tools2_defaults_form.tools2_cfill_group.margin_entry,
  1399. "tools_copper_thieving_reference": self.ui.tools2_defaults_form.tools2_cfill_group.reference_radio,
  1400. "tools_copper_thieving_box_type": self.ui.tools2_defaults_form.tools2_cfill_group.bbox_type_radio,
  1401. "tools_copper_thieving_circle_steps": self.ui.tools2_defaults_form.tools2_cfill_group.circlesteps_entry,
  1402. "tools_copper_thieving_fill_type": self.ui.tools2_defaults_form.tools2_cfill_group.fill_type_radio,
  1403. "tools_copper_thieving_dots_dia": self.ui.tools2_defaults_form.tools2_cfill_group.dot_dia_entry,
  1404. "tools_copper_thieving_dots_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.dot_spacing_entry,
  1405. "tools_copper_thieving_squares_size": self.ui.tools2_defaults_form.tools2_cfill_group.square_size_entry,
  1406. "tools_copper_thieving_squares_spacing":
  1407. self.ui.tools2_defaults_form.tools2_cfill_group.squares_spacing_entry,
  1408. "tools_copper_thieving_lines_size": self.ui.tools2_defaults_form.tools2_cfill_group.line_size_entry,
  1409. "tools_copper_thieving_lines_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.lines_spacing_entry,
  1410. "tools_copper_thieving_rb_margin": self.ui.tools2_defaults_form.tools2_cfill_group.rb_margin_entry,
  1411. "tools_copper_thieving_rb_thickness": self.ui.tools2_defaults_form.tools2_cfill_group.rb_thickness_entry,
  1412. "tools_copper_thieving_mask_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_ppm_entry,
  1413. # Fiducials Tool
  1414. "tools_fiducials_dia": self.ui.tools2_defaults_form.tools2_fiducials_group.dia_entry,
  1415. "tools_fiducials_margin": self.ui.tools2_defaults_form.tools2_fiducials_group.margin_entry,
  1416. "tools_fiducials_mode": self.ui.tools2_defaults_form.tools2_fiducials_group.mode_radio,
  1417. "tools_fiducials_second_pos": self.ui.tools2_defaults_form.tools2_fiducials_group.pos_radio,
  1418. "tools_fiducials_type": self.ui.tools2_defaults_form.tools2_fiducials_group.fid_type_radio,
  1419. "tools_fiducials_line_thickness": self.ui.tools2_defaults_form.tools2_fiducials_group.line_thickness_entry,
  1420. # Calibration Tool
  1421. "tools_cal_calsource": self.ui.tools2_defaults_form.tools2_cal_group.cal_source_radio,
  1422. "tools_cal_travelz": self.ui.tools2_defaults_form.tools2_cal_group.travelz_entry,
  1423. "tools_cal_verz": self.ui.tools2_defaults_form.tools2_cal_group.verz_entry,
  1424. "tools_cal_zeroz": self.ui.tools2_defaults_form.tools2_cal_group.zeroz_cb,
  1425. "tools_cal_toolchangez": self.ui.tools2_defaults_form.tools2_cal_group.toolchangez_entry,
  1426. "tools_cal_toolchange_xy": self.ui.tools2_defaults_form.tools2_cal_group.toolchange_xy_entry,
  1427. "tools_cal_sec_point": self.ui.tools2_defaults_form.tools2_cal_group.second_point_radio,
  1428. # Extract Drills Tool
  1429. "tools_edrills_hole_type": self.ui.tools2_defaults_form.tools2_edrills_group.hole_size_radio,
  1430. "tools_edrills_hole_fixed_dia": self.ui.tools2_defaults_form.tools2_edrills_group.dia_entry,
  1431. "tools_edrills_hole_prop_factor": self.ui.tools2_defaults_form.tools2_edrills_group.factor_entry,
  1432. "tools_edrills_circular_ring": self.ui.tools2_defaults_form.tools2_edrills_group.circular_ring_entry,
  1433. "tools_edrills_oblong_ring": self.ui.tools2_defaults_form.tools2_edrills_group.oblong_ring_entry,
  1434. "tools_edrills_square_ring": self.ui.tools2_defaults_form.tools2_edrills_group.square_ring_entry,
  1435. "tools_edrills_rectangular_ring": self.ui.tools2_defaults_form.tools2_edrills_group.rectangular_ring_entry,
  1436. "tools_edrills_others_ring": self.ui.tools2_defaults_form.tools2_edrills_group.other_ring_entry,
  1437. "tools_edrills_circular": self.ui.tools2_defaults_form.tools2_edrills_group.circular_cb,
  1438. "tools_edrills_oblong": self.ui.tools2_defaults_form.tools2_edrills_group.oblong_cb,
  1439. "tools_edrills_square": self.ui.tools2_defaults_form.tools2_edrills_group.square_cb,
  1440. "tools_edrills_rectangular": self.ui.tools2_defaults_form.tools2_edrills_group.rectangular_cb,
  1441. "tools_edrills_others": self.ui.tools2_defaults_form.tools2_edrills_group.other_cb,
  1442. # Punch Gerber Tool
  1443. "tools_punch_hole_type": self.ui.tools2_defaults_form.tools2_punch_group.hole_size_radio,
  1444. "tools_punch_hole_fixed_dia": self.ui.tools2_defaults_form.tools2_punch_group.dia_entry,
  1445. "tools_punch_hole_prop_factor": self.ui.tools2_defaults_form.tools2_punch_group.factor_entry,
  1446. "tools_punch_circular_ring": self.ui.tools2_defaults_form.tools2_punch_group.circular_ring_entry,
  1447. "tools_punch_oblong_ring": self.ui.tools2_defaults_form.tools2_punch_group.oblong_ring_entry,
  1448. "tools_punch_square_ring": self.ui.tools2_defaults_form.tools2_punch_group.square_ring_entry,
  1449. "tools_punch_rectangular_ring": self.ui.tools2_defaults_form.tools2_punch_group.rectangular_ring_entry,
  1450. "tools_punch_others_ring": self.ui.tools2_defaults_form.tools2_punch_group.other_ring_entry,
  1451. "tools_punch_circular": self.ui.tools2_defaults_form.tools2_punch_group.circular_cb,
  1452. "tools_punch_oblong": self.ui.tools2_defaults_form.tools2_punch_group.oblong_cb,
  1453. "tools_punch_square": self.ui.tools2_defaults_form.tools2_punch_group.square_cb,
  1454. "tools_punch_rectangular": self.ui.tools2_defaults_form.tools2_punch_group.rectangular_cb,
  1455. "tools_punch_others": self.ui.tools2_defaults_form.tools2_punch_group.other_cb,
  1456. # Utilities
  1457. # File associations
  1458. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  1459. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  1460. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  1461. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  1462. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  1463. }
  1464. # update the Preferences GUI elements with the values in the self.defaults
  1465. self.defaults_write_form()
  1466. # When the self.defaults dictionary changes will update the Preferences GUI forms
  1467. self.defaults.set_change_callback(self.on_defaults_dict_change)
  1468. # ##############################################################################
  1469. # ########################## FIRST RUN SECTION #################################
  1470. # ##################### It's done only once after install ####################
  1471. # ##############################################################################
  1472. if self.defaults["first_run"] is True:
  1473. self.save_factory_defaults(silent_message=False)
  1474. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  1475. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1476. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1477. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1478. initial_lay = 'compact'
  1479. self.on_layout(lay=initial_lay)
  1480. # Set the combobox in Preferences to the current layout
  1481. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  1482. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  1483. # after the first run, this object should be False
  1484. self.defaults["first_run"] = False
  1485. self.save_defaults(silent=True)
  1486. # #############################################################################
  1487. # ############################## Data #########################################
  1488. # #############################################################################
  1489. self.recent = []
  1490. self.recent_projects = []
  1491. self.clipboard = QtWidgets.QApplication.clipboard()
  1492. self.project_filename = None
  1493. self.toggle_units_ignore = False
  1494. # #############################################################################
  1495. # ########################## LOAD PREPROCESSORS ###############################
  1496. # #############################################################################
  1497. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  1498. # the preprocessor file
  1499. self.preprocessors = load_preprocessors(self)
  1500. # make sure that always the 'default' preprocessor is the first item in the dictionary
  1501. if 'default' in self.preprocessors.keys():
  1502. new_ppp_dict = dict()
  1503. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  1504. default_pp = self.preprocessors.pop('default')
  1505. new_ppp_dict['default'] = default_pp
  1506. # then add the rest of the keys
  1507. for name, val_class in self.preprocessors.items():
  1508. new_ppp_dict[name] = val_class
  1509. # and now put back the ordered dict with 'default' key first
  1510. self.preprocessors = new_ppp_dict
  1511. for name in list(self.preprocessors.keys()):
  1512. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  1513. if name.partition('_')[0] == 'Paste':
  1514. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  1515. continue
  1516. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1517. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  1518. if name == 'hpgl':
  1519. continue
  1520. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1521. # #############################################################################
  1522. # ########################## LOAD LANGUAGES ##################################
  1523. # #############################################################################
  1524. self.languages = fcTranslate.load_languages()
  1525. for name in sorted(self.languages.values()):
  1526. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  1527. # #############################################################################
  1528. # ############################ APPLY APP LANGUAGE #############################
  1529. # #############################################################################
  1530. ret_val = fcTranslate.apply_language('strings')
  1531. if ret_val == "no language":
  1532. self.inform.emit('[ERROR] %s' %
  1533. _("Could not find the Language files. The App strings are missing."))
  1534. log.debug("Could not find the Language files. The App strings are missing.")
  1535. else:
  1536. # make the current language the current selection on the language combobox
  1537. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1538. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1539. # #############################################################################
  1540. # ########################### CREATE UNIQUE SERIAL NUMBER #####################
  1541. # #############################################################################
  1542. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1543. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1544. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1545. self.save_defaults(silent=True, first_time=True)
  1546. self.propagate_defaults(silent=True)
  1547. # def auto_save_defaults():
  1548. # try:
  1549. # self.save_defaults(silent=True)
  1550. # self.propagate_defaults(silent=True)
  1551. # finally:
  1552. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1553. # the following lines activates automatic defaults save
  1554. # if user_defaults:
  1555. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1556. # #############################################################################
  1557. # ########################### UPDATE THE OPTIONS ##############################
  1558. # #############################################################################
  1559. self.options = LoudDict()
  1560. # ----------------------------------------------------------------------------------------------------
  1561. # Update the self.options from the self.defaults
  1562. # The self.defaults holds the application defaults while the self.options holds the object defaults
  1563. # -----------------------------------------------------------------------------------------------------
  1564. # Copy app defaults to project options
  1565. for def_key, def_val in self.defaults.items():
  1566. self.options[def_key] = deepcopy(def_val)
  1567. # self.options.update(self.defaults)
  1568. self.gen_form = None
  1569. self.ger_form = None
  1570. self.exc_form = None
  1571. self.geo_form = None
  1572. self.cnc_form = None
  1573. self.tools_form = None
  1574. self.tools2_form = None
  1575. self.fa_form = None
  1576. # Will show the Preferences GUI
  1577. self.show_preferences_gui()
  1578. # Initialize the color box's color in Preferences -> Global -> Color
  1579. self.init_color_pickers_in_preferences_gui()
  1580. # ### End of Data ####
  1581. # #############################################################################
  1582. # ######################## SETUP OBJECT COLLECTION ############################
  1583. # #############################################################################
  1584. self.collection = ObjectCollection(self)
  1585. self.ui.project_tab_layout.addWidget(self.collection.view)
  1586. # ### Adjust tabs width ## ##
  1587. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1588. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1589. self.collection.view.setMinimumWidth(290)
  1590. self.log.debug("Finished creating Object Collection.")
  1591. # #############################################################################
  1592. # ############################## SETUP Plot Area ##############################
  1593. # #############################################################################
  1594. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1595. if self.defaults["global_graphic_engine"] == '3D':
  1596. self.is_legacy = False
  1597. else:
  1598. self.is_legacy = True
  1599. # Event signals disconnect id holders
  1600. self.mp = None
  1601. self.mm = None
  1602. self.mr = None
  1603. self.mdc = None
  1604. self.mp_zc = None
  1605. self.kp = None
  1606. # Matplotlib axis
  1607. self.axes = None
  1608. if show_splash:
  1609. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1610. "Canvas initialization started."),
  1611. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1612. color=QtGui.QColor("gray"))
  1613. start_plot_time = time.time() # debug
  1614. self.plotcanvas = None
  1615. self.app_cursor = None
  1616. self.hover_shapes = None
  1617. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  1618. # setup the PlotCanvas
  1619. self.on_plotcanvas_setup()
  1620. end_plot_time = time.time()
  1621. self.used_time = end_plot_time - start_plot_time
  1622. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1623. if show_splash:
  1624. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1625. "Canvas initialization started.\n"
  1626. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1627. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1628. color=QtGui.QColor("gray"))
  1629. self.ui.splitter.setStretchFactor(1, 2)
  1630. # #############################################################################
  1631. # ################################### SYS TRAY ################################
  1632. # #############################################################################
  1633. if self.defaults["global_systray_icon"]:
  1634. self.parent_w = QtWidgets.QWidget()
  1635. if self.cmd_line_headless == 1:
  1636. self.trayIcon = FlatCAMSystemTray(app=self,
  1637. icon=QtGui.QIcon(self.resource_location +
  1638. '/flatcam_icon32_green.png'),
  1639. headless=True,
  1640. parent=self.parent_w)
  1641. else:
  1642. self.trayIcon = FlatCAMSystemTray(app=self,
  1643. icon=QtGui.QIcon(self.resource_location +
  1644. '/flatcam_icon32_green.png'),
  1645. parent=self.parent_w)
  1646. # #############################################################################
  1647. # ################################## Worker SETUP #############################
  1648. # #############################################################################
  1649. if self.defaults["global_worker_number"]:
  1650. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1651. else:
  1652. self.workers = WorkerStack(workers_number=2)
  1653. self.worker_task.connect(self.workers.add_task)
  1654. self.log.debug("Finished creating Workers crew.")
  1655. # #############################################################################
  1656. # ################################# Activity Monitor ##########################
  1657. # #############################################################################
  1658. self.activity_view = FlatCAMActivityView(app=self)
  1659. self.ui.infobar.addWidget(self.activity_view)
  1660. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1661. # #############################################################################
  1662. # ################################## Signal handling ##########################
  1663. # #############################################################################
  1664. # ################################# Custom signals ###########################
  1665. # signal for displaying messages in status bar
  1666. self.inform.connect(self.info)
  1667. # signal to be called when the app is quiting
  1668. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  1669. self.message.connect(self.message_dialog)
  1670. # self.progress.connect(self.set_progress_bar)
  1671. # signals that are emitted when object state changes
  1672. self.object_created.connect(self.on_object_created)
  1673. self.object_changed.connect(self.on_object_changed)
  1674. self.object_plotted.connect(self.on_object_plotted)
  1675. self.plots_updated.connect(self.on_plots_updated)
  1676. # signals emitted when file state change
  1677. self.file_opened.connect(self.register_recent)
  1678. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1679. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1680. # ############# Standard signals ###################
  1681. # ### Menu
  1682. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1683. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1684. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1685. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1686. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1687. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1688. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1689. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1690. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1691. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1692. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1693. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1694. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1695. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1696. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1697. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1698. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1699. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  1700. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1701. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1702. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1703. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1704. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1705. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  1706. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1707. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1708. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1709. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1710. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1711. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1712. self.ui.menufile_exit.triggered.connect(self.final_save)
  1713. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1714. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1715. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1716. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1717. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1718. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1719. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1720. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1721. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  1722. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1723. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1724. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1725. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  1726. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1727. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1728. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1729. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1730. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1731. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1732. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1733. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1734. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1735. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1736. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1737. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1738. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1739. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1740. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1741. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1742. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1743. self.ui.menuoptions_tools_db.triggered.connect(self.on_tools_database)
  1744. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1745. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1746. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1747. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1748. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1749. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1750. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1751. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1752. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1753. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1754. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1755. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1756. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1757. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  1758. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1759. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1760. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1761. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1762. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1763. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1764. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1765. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1766. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1767. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1768. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1769. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1770. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1771. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1772. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  1773. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1774. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1775. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1776. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1777. # ToolBar signals
  1778. self.connect_toolbar_signals()
  1779. # Notebook and Plot Tab Area signals
  1780. # make the right click on the notebook tab and plot tab area tab raise a menu
  1781. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1782. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1783. self.on_tab_setup_context_menu()
  1784. # activate initial state
  1785. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1786. # Context Menu
  1787. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1788. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1789. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1790. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1791. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1792. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1793. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1794. self.ui.clearplot.triggered.connect(self.clear_plots)
  1795. self.ui.replot.triggered.connect(self.plot_all)
  1796. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  1797. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1798. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1799. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1800. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1801. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1802. # Project Context Menu -> Color Setting
  1803. for act in self.ui.menuprojectcolor.actions():
  1804. act.triggered.connect(self.on_set_color_action_triggered)
  1805. # Preferences Plot Area TAB
  1806. self.ui.pref_save_button.clicked.connect(lambda: self.on_save_button(save_to_file=True))
  1807. self.ui.pref_apply_button.clicked.connect(lambda: self.on_save_button(save_to_file=False))
  1808. self.ui.pref_close_button.clicked.connect(self.on_pref_close_button)
  1809. self.ui.pref_defaults_button.clicked.connect(self.on_restore_defaults_preferences)
  1810. # #############################################################################
  1811. # ######################### GUI PREFERENCES SIGNALS ###########################
  1812. # #############################################################################
  1813. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1814. lambda: self.on_toggle_units(no_pref=False))
  1815. # ############################# Workspace Setting Signals #####################
  1816. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  1817. self.on_workspace_modified)
  1818. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  1819. self.on_workspace_modified
  1820. )
  1821. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1822. self.ui.general_defaults_form.general_gui_group.layout_combo.activated.connect(self.on_layout)
  1823. # #############################################################################
  1824. # ############################# GUI SETTINGS SIGNALS ##########################
  1825. # #############################################################################
  1826. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1827. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1828. # ########## Tools related signals #############
  1829. # Film Tool
  1830. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1831. self.on_film_color_entry)
  1832. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1833. self.on_film_color_button)
  1834. # QRCode Tool
  1835. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  1836. self.on_qrcode_fill_color_entry)
  1837. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  1838. self.on_qrcode_fill_color_button)
  1839. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  1840. self.on_qrcode_back_color_entry)
  1841. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  1842. self.on_qrcode_back_color_button)
  1843. # portability changed signal
  1844. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1845. # Object list
  1846. self.collection.view.activated.connect(self.on_row_activated)
  1847. self.collection.item_selected.connect(self.on_row_selected)
  1848. self.object_status_changed.connect(self.on_collection_updated)
  1849. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1850. # Export Excellon parameters.
  1851. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1852. self.on_update_exc_export
  1853. )
  1854. # call it once to make sure it is updated at startup
  1855. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1856. # when there are arguments at application startup this get launched
  1857. self.args_at_startup[list].connect(self.on_startup_args)
  1858. # #############################################################################
  1859. # ########################## FILE ASSOCIATIONS SIGNALS ########################
  1860. # #############################################################################
  1861. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1862. lambda: self.restore_extensions(ext_type='excellon'))
  1863. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1864. lambda: self.restore_extensions(ext_type='gcode'))
  1865. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1866. lambda: self.restore_extensions(ext_type='gerber'))
  1867. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1868. lambda: self.delete_all_extensions(ext_type='excellon'))
  1869. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1870. lambda: self.delete_all_extensions(ext_type='gcode'))
  1871. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1872. lambda: self.delete_all_extensions(ext_type='gerber'))
  1873. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1874. lambda: self.add_extension(ext_type='excellon'))
  1875. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1876. lambda: self.add_extension(ext_type='gcode'))
  1877. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1878. lambda: self.add_extension(ext_type='gerber'))
  1879. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1880. lambda: self.del_extension(ext_type='excellon'))
  1881. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1882. lambda: self.del_extension(ext_type='gcode'))
  1883. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1884. lambda: self.del_extension(ext_type='gerber'))
  1885. # connect the 'Apply' buttons from the Preferences/File Associations
  1886. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1887. lambda: self.on_register_files(obj_type='excellon'))
  1888. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1889. lambda: self.on_register_files(obj_type='gcode'))
  1890. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1891. lambda: self.on_register_files(obj_type='gerber'))
  1892. # #############################################################################
  1893. # ################################ KEYWORDS SIGNALS ###########################
  1894. # #############################################################################
  1895. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1896. lambda: self.restore_extensions(ext_type='keyword'))
  1897. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1898. lambda: self.delete_all_extensions(ext_type='keyword'))
  1899. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1900. lambda: self.add_extension(ext_type='keyword'))
  1901. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1902. lambda: self.del_extension(ext_type='keyword'))
  1903. # connect the abort_all_tasks related slots to the related signals
  1904. self.proc_container.idle_flag.connect(self.app_is_idle)
  1905. # signal emitted when a tab is closed in the Plot Area
  1906. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1907. self.ui.grid_snap_btn.triggered.connect(self.on_grid_snap_triggered)
  1908. # signal to close the application
  1909. self.close_app_signal.connect(self.kill_app)
  1910. # #####################################################################################
  1911. # ########### FINISHED CONNECTING SIGNALS #############################################
  1912. # #####################################################################################
  1913. self.log.debug("Finished connecting Signals.")
  1914. # #####################################################################################
  1915. # ########################## Other setups #############################################
  1916. # #####################################################################################
  1917. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1918. # depending on from where those tools are called different actions can be done
  1919. self.call_source = 'app'
  1920. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1921. self.tool_tab_locked = False
  1922. # decide if to show or hide the Notebook side of the screen at startup
  1923. if self.defaults["global_project_at_startup"] is True:
  1924. self.ui.splitter.setSizes([1, 1])
  1925. else:
  1926. self.ui.splitter.setSizes([0, 1])
  1927. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1928. self.setup_component_editor()
  1929. # #####################################################################################
  1930. # ######################### Auto-complete KEYWORDS ####################################
  1931. # #####################################################################################
  1932. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1933. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1934. 'delete', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon', 'ee', 'export_exc',
  1935. 'export_gcode', 'export_gerber', 'egr', 'export_svg', 'ext', 'exteriors', 'follow',
  1936. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1937. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1938. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1939. 'mirror', 'ncc',
  1940. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1941. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1942. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1943. 'save', 'save_project',
  1944. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1945. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1946. 'version', 'write_gcode'
  1947. ]
  1948. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1949. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1950. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis',
  1951. 'axisoffset',
  1952. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1953. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz',
  1954. 'dwelltime', 'extracut_length',
  1955. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  1956. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1957. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  1958. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1959. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1960. 'spacing_columns',
  1961. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'toolchangez',
  1962. 'tooldia', 'use_threads', 'value',
  1963. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1964. ]
  1965. self.tcl_keywords = [
  1966. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1967. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1968. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1969. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1970. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1971. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1972. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1973. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1974. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1975. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1976. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1977. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1978. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1979. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1980. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1981. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1982. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1983. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1984. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1985. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1986. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1987. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1988. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1989. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1990. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1991. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1992. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1993. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1994. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1995. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1996. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1997. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1998. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1999. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  2000. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  2001. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  2002. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  2003. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  2004. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  2005. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  2006. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  2007. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  2008. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  2009. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  2010. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  2011. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  2012. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  2013. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  2014. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  2015. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  2016. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  2017. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  2018. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  2019. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  2020. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  2021. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  2022. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  2023. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  2024. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  2025. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  2026. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  2027. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  2028. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  2029. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  2030. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  2031. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  2032. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  2033. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  2034. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  2035. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  2036. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  2037. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  2038. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  2039. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  2040. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  2041. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  2042. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  2043. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  2044. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  2045. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  2046. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  2047. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  2048. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  2049. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  2050. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  2051. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  2052. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  2053. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  2054. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  2055. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  2056. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  2057. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  2058. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  2059. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  2060. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  2061. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  2062. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  2063. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  2064. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  2065. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  2066. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  2067. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  2068. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  2069. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  2070. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  2071. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  2072. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  2073. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  2074. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  2075. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  2076. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  2077. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  2078. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  2079. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  2080. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  2081. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  2082. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  2083. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  2084. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  2085. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  2086. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  2087. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  2088. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  2089. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  2090. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  2091. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  2092. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  2093. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  2094. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  2095. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  2096. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  2097. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  2098. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  2099. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  2100. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  2101. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  2102. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  2103. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  2104. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  2105. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  2106. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  2107. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  2108. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  2109. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  2110. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  2111. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  2112. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  2113. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  2114. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  2115. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  2116. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  2117. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  2118. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  2119. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  2120. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  2121. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  2122. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  2123. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  2124. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  2125. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  2126. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  2127. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  2128. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  2129. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  2130. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  2131. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  2132. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  2133. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  2134. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  2135. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  2136. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  2137. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  2138. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  2139. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  2140. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  2141. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  2142. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  2143. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  2144. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  2145. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  2146. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  2147. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  2148. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  2149. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  2150. ]
  2151. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  2152. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2153. # ####################################################################################
  2154. # ####################### Shell SETUP ################################################
  2155. # ####################################################################################
  2156. # this will hold the TCL instance
  2157. self.tcl = None
  2158. self.init_tcl()
  2159. self.shell = FCShell(self, version=self.version)
  2160. self.shell._edit.set_model_data(self.myKeywords)
  2161. self.shell.setWindowIcon(self.ui.app_icon)
  2162. self.shell.setWindowTitle("FlatCAM Shell")
  2163. self.shell.resize(*self.defaults["global_shell_shape"])
  2164. self.shell.append_output("FlatCAM %s - " % self.version)
  2165. self.shell.append_output(_("Type >help< to get started\n\n"))
  2166. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2167. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2168. self.ui.shell_dock.setWidget(self.shell)
  2169. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2170. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2171. QtWidgets.QDockWidget.DockWidgetFloatable |
  2172. QtWidgets.QDockWidget.DockWidgetClosable)
  2173. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2174. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2175. if self.defaults["global_shell_at_startup"]:
  2176. self.ui.shell_dock.show()
  2177. else:
  2178. self.ui.shell_dock.hide()
  2179. # ##################################################################################
  2180. # ###################### Tools and Plugins #########################################
  2181. # ##################################################################################
  2182. self.dblsidedtool = None
  2183. self.distance_tool = None
  2184. self.distance_min_tool = None
  2185. self.panelize_tool = None
  2186. self.film_tool = None
  2187. self.paste_tool = None
  2188. self.calculator_tool = None
  2189. self.rules_tool = None
  2190. self.sub_tool = None
  2191. self.move_tool = None
  2192. self.cutout_tool = None
  2193. self.ncclear_tool = None
  2194. self.optimal_tool = None
  2195. self.paint_tool = None
  2196. self.transform_tool = None
  2197. self.properties_tool = None
  2198. self.pdf_tool = None
  2199. self.image_tool = None
  2200. self.pcb_wizard_tool = None
  2201. self.cal_exc_tool = None
  2202. self.qrcode_tool = None
  2203. self.copper_thieving_tool = None
  2204. self.fiducial_tool = None
  2205. self.edrills_tool = None
  2206. self.align_objects_tool = None
  2207. self.punch_tool = None
  2208. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2209. try:
  2210. self.install_tools()
  2211. except AttributeError as e:
  2212. log.debug("App.__init__() install tools() --> %s" % str(e))
  2213. # ##################################################################################
  2214. # ########################### SETUP RECENT ITEMS ###################################
  2215. # ##################################################################################
  2216. self.setup_recent_items()
  2217. # ##################################################################################
  2218. # ########################### BookMarks Manager ####################################
  2219. # ##################################################################################
  2220. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  2221. self.install_bookmarks()
  2222. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  2223. # ##################################################################################
  2224. # ############################## Tools Database ####################################
  2225. # ##################################################################################
  2226. self.tools_db_tab = None
  2227. # ### System Font Parsing ###
  2228. # self.f_parse = ParseFont(self)
  2229. # self.parse_system_fonts()
  2230. # #####################################################################################
  2231. # ######################## Check for updates ##########################################
  2232. # #####################################################################################
  2233. # Separate thread (Not worker)
  2234. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2235. if (self.beta is False or self.beta is None) and \
  2236. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  2237. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2238. self.thr2 = QtCore.QThread()
  2239. self.worker_task.emit({'fcn': self.version_check,
  2240. 'params': []})
  2241. self.thr2.start(QtCore.QThread.LowPriority)
  2242. # #####################################################################################
  2243. # ######################### Register files with FlatCAM; #############################
  2244. # ######################### It works only for Windows for now ########################
  2245. # #####################################################################################
  2246. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2247. self.on_register_files()
  2248. # #####################################################################################
  2249. # ###################### Variables for global usage ###################################
  2250. # #####################################################################################
  2251. # hold the App units
  2252. self.units = 'MM'
  2253. # coordinates for relative position display
  2254. self.rel_point1 = (0, 0)
  2255. self.rel_point2 = (0, 0)
  2256. # variable to store coordinates
  2257. self.pos = (0, 0)
  2258. self.pos_canvas = (0, 0)
  2259. self.pos_jump = (0, 0)
  2260. # variable to store mouse coordinates
  2261. self.mouse = [0, 0]
  2262. # decide if we have a double click or single click
  2263. self.doubleclick = False
  2264. # store here the is_dragging value
  2265. self.event_is_dragging = False
  2266. # variable to store if a command is active (then the var is not None) and which one it is
  2267. self.command_active = None
  2268. # variable to store the status of moving selection action
  2269. # None value means that it's not an selection action
  2270. # True value = a selection from left to right
  2271. # False value = a selection from right to left
  2272. self.selection_type = None
  2273. # List to store the objects that are currently loaded in FlatCAM
  2274. # This list is updated on each object creation or object delete
  2275. self.all_objects_list = list()
  2276. # List to store the objects that are selected
  2277. self.sel_objects_list = list()
  2278. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2279. self.key_modifiers = None
  2280. # Variable to hold the status of the axis
  2281. self.toggle_axis = True
  2282. # Variable to hold the status of the grid lines
  2283. self.toggle_grid_lines = True
  2284. # Variable to store the status of the fullscreen event
  2285. self.toggle_fscreen = False
  2286. # Variable to store the status of the code editor
  2287. self.toggle_codeeditor = False
  2288. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2289. self.click_noproject = False
  2290. self.cursor = None
  2291. # Variable to store the GCODE that was edited
  2292. self.gcode_edited = ""
  2293. self.text_editor_tab = None
  2294. # reference for the self.ui.code_editor
  2295. self.reference_code_editor = None
  2296. self.script_code = ''
  2297. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2298. self.preferences_changed_flag = False
  2299. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  2300. self.tools_db_changed_flag = False
  2301. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2302. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2303. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2304. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2305. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2306. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2307. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  2308. 'sbp', 'tap', 'xpi']
  2309. self.svg_list = ['svg']
  2310. self.dxf_list = ['dxf']
  2311. self.pdf_list = ['pdf']
  2312. self.prj_list = ['flatprj']
  2313. self.conf_list = ['flatconfig']
  2314. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2315. # flag for polygons not cleared
  2316. self.poly_not_cleared = False
  2317. # VisPy visuals
  2318. self.isHovering = False
  2319. self.notHovering = True
  2320. # Window geometry
  2321. self.x_pos = None
  2322. self.y_pos = None
  2323. self.width = None
  2324. self.height = None
  2325. # when True, the app has to return from any thread
  2326. self.abort_flag = False
  2327. # set the value used in the Windows Title
  2328. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2329. # this holds a widget that is installed in the Plot Area when View Source option is used
  2330. self.source_editor_tab = None
  2331. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  2332. # VisPy visuals
  2333. if self.is_legacy is False:
  2334. try:
  2335. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  2336. except AttributeError:
  2337. self.tool_shapes = None
  2338. else:
  2339. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  2340. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  2341. # used in the delayed shutdown self.start_delayed_quit() method
  2342. self.save_timer = None
  2343. # ###############################################################################
  2344. # ################# ADDING FlatCAM EDITORS section ##############################
  2345. # ###############################################################################
  2346. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2347. # at the first launch of the App , the editors will not be functional.
  2348. try:
  2349. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2350. except AttributeError:
  2351. pass
  2352. try:
  2353. self.exc_editor = FlatCAMExcEditor(self)
  2354. except AttributeError:
  2355. pass
  2356. try:
  2357. self.grb_editor = FlatCAMGrbEditor(self)
  2358. except AttributeError:
  2359. pass
  2360. self.log.debug("Finished adding FlatCAM Editor's.")
  2361. self.set_ui_title(name=_("New Project - Not saved"))
  2362. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2363. current_platform = platform.architecture()[0]
  2364. if current_platform != '64bit':
  2365. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2366. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2367. # ###############################################################################
  2368. # ####################### Finished the CONSTRUCTOR ##############################
  2369. # ###############################################################################
  2370. App.log.debug("END of constructor. Releasing control.")
  2371. # #####################################################################################
  2372. # ########################## SHOW GUI #################################################
  2373. # #####################################################################################
  2374. # if the app is not started as headless, show it
  2375. if self.cmd_line_headless != 1:
  2376. if show_splash:
  2377. # finish the splash
  2378. self.splash.finish(self.ui)
  2379. mgui_settings = QSettings("Open Source", "FlatCAM")
  2380. if mgui_settings.contains("maximized_gui"):
  2381. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  2382. if maximized_ui is True:
  2383. self.ui.showMaximized()
  2384. else:
  2385. self.ui.show()
  2386. else:
  2387. self.ui.show()
  2388. if self.defaults["global_systray_icon"]:
  2389. self.trayIcon.show()
  2390. else:
  2391. log.warning("******************* RUNNING HEADLESS *******************")
  2392. # #####################################################################################
  2393. # ########################## START-UP ARGUMENTS #######################################
  2394. # #####################################################################################
  2395. # test if the program was started with a script as parameter
  2396. if self.cmd_line_shellvar:
  2397. try:
  2398. cnt = 0
  2399. command_tcl = 0
  2400. for i in self.cmd_line_shellvar.split(','):
  2401. if i is not None:
  2402. # noinspection PyBroadException
  2403. try:
  2404. command_tcl = eval(i)
  2405. except Exception:
  2406. command_tcl = i
  2407. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2408. cnt += 1
  2409. # if there are Windows paths then replace the path separator with a Unix like one
  2410. if sys.platform == 'win32':
  2411. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2412. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2413. except Exception as ext:
  2414. print("ERROR: ", ext)
  2415. sys.exit(2)
  2416. if self.cmd_line_shellfile:
  2417. if self.cmd_line_headless != 1:
  2418. if self.ui.shell_dock.isHidden():
  2419. self.ui.shell_dock.show()
  2420. try:
  2421. with open(self.cmd_line_shellfile, "r") as myfile:
  2422. # if show_splash:
  2423. # self.splash.showMessage('%s: %ssec\n%s' % (
  2424. # _("Canvas initialization started.\n"
  2425. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  2426. # _("Executing Tcl Script ...")),
  2427. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  2428. # color=QtGui.QColor("gray"))
  2429. cmd_line_shellfile_text = myfile.read()
  2430. if self.cmd_line_headless != 1:
  2431. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2432. else:
  2433. self.shell._sysShell.exec_command(cmd_line_shellfile_text, no_echo=True)
  2434. except Exception as ext:
  2435. print("ERROR: ", ext)
  2436. sys.exit(2)
  2437. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2438. # the path/file_name must be enclosed in quotes if it contain spaces
  2439. if App.args:
  2440. self.args_at_startup.emit(App.args)
  2441. if self.old_defaults_found is True:
  2442. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  2443. "Please reboot the application to update."))
  2444. self.old_defaults_found = False
  2445. @staticmethod
  2446. def copy_and_overwrite(from_path, to_path):
  2447. """
  2448. From here:
  2449. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2450. :param from_path: source path
  2451. :param to_path: destination path
  2452. :return: None
  2453. """
  2454. if os.path.exists(to_path):
  2455. shutil.rmtree(to_path)
  2456. try:
  2457. shutil.copytree(from_path, to_path)
  2458. except FileNotFoundError:
  2459. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2460. shutil.copytree(from_new_path, to_path)
  2461. def on_startup_args(self, args, silent=False):
  2462. """
  2463. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2464. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  2465. :param args: a list containing the application args at startup
  2466. :return: None
  2467. """
  2468. if args is not None:
  2469. args_to_process = args
  2470. else:
  2471. args_to_process = App.args
  2472. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2473. for argument in args_to_process:
  2474. if '.FlatPrj'.lower() in argument.lower():
  2475. try:
  2476. project_name = str(argument)
  2477. if project_name == "":
  2478. if silent is False:
  2479. self.inform.emit(_("Open cancelled."))
  2480. else:
  2481. # self.open_project(project_name)
  2482. run_from_arg = True
  2483. # self.worker_task.emit({'fcn': self.open_project,
  2484. # 'params': [project_name, run_from_arg]})
  2485. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2486. except Exception as e:
  2487. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2488. elif '.FlatConfig'.lower() in argument.lower():
  2489. try:
  2490. file_name = str(argument)
  2491. if file_name == "":
  2492. if silent is False:
  2493. self.inform.emit(_("Open Config file failed."))
  2494. else:
  2495. run_from_arg = True
  2496. # self.worker_task.emit({'fcn': self.open_config_file,
  2497. # 'params': [file_name, run_from_arg]})
  2498. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2499. except Exception as e:
  2500. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2501. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2502. try:
  2503. file_name = str(argument)
  2504. if file_name == "":
  2505. if silent is False:
  2506. self.inform.emit(_("Open Script file failed."))
  2507. else:
  2508. if silent is False:
  2509. self.on_fileopenscript(name=file_name)
  2510. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2511. self.on_filerunscript(name=file_name)
  2512. except Exception as e:
  2513. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2514. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2515. log.debug("App.on_startup_args() --> Quit event.")
  2516. sys.exit()
  2517. elif 'save'.lower() in argument.lower():
  2518. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2519. self.save_defaults()
  2520. else:
  2521. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2522. proc_arg = argument.lower()
  2523. for ext in exc_list:
  2524. proc_ext = ext.replace(' ', '')
  2525. proc_ext = '.%s' % proc_ext
  2526. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2527. file_name = str(argument)
  2528. if file_name == "":
  2529. if silent is False:
  2530. self.inform.emit(_("Open Excellon file failed."))
  2531. else:
  2532. self.on_fileopenexcellon(name=file_name)
  2533. return
  2534. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2535. for ext in gco_list:
  2536. proc_ext = ext.replace(' ', '')
  2537. proc_ext = '.%s' % proc_ext
  2538. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2539. file_name = str(argument)
  2540. if file_name == "":
  2541. if silent is False:
  2542. self.inform.emit(_("Open GCode file failed."))
  2543. else:
  2544. self.on_fileopengcode(name=file_name)
  2545. return
  2546. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2547. for ext in grb_list:
  2548. proc_ext = ext.replace(' ', '')
  2549. proc_ext = '.%s' % proc_ext
  2550. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2551. file_name = str(argument)
  2552. if file_name == "":
  2553. if silent is False:
  2554. self.inform.emit(_("Open Gerber file failed."))
  2555. else:
  2556. self.on_fileopengerber(name=file_name)
  2557. return
  2558. # if it reached here without already returning then the app was registered with a file that it does not
  2559. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2560. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2561. # for arg in args_to_process:
  2562. # if 'FlatCAM.exe' in arg:
  2563. # continue
  2564. # else:
  2565. # sys.exit(2)
  2566. def set_ui_title(self, name):
  2567. """
  2568. Sets the title of the main window.
  2569. :param name: String that store the project path and project name
  2570. :return: None
  2571. """
  2572. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2573. (self.version,
  2574. ('BETA' if self.beta else ''),
  2575. platform.architecture()[0],
  2576. self.engine,
  2577. name)
  2578. )
  2579. def on_app_restart(self):
  2580. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2581. # be left in the SySTray
  2582. try:
  2583. self.trayIcon.hide()
  2584. except Exception:
  2585. pass
  2586. fcTranslate.restart_program(app=self)
  2587. def defaults_read_form(self):
  2588. """
  2589. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2590. :return: None
  2591. """
  2592. for option in self.defaults_form_fields:
  2593. try:
  2594. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2595. except Exception as e:
  2596. log.debug("App.defaults_read_form() --> %s" % str(e))
  2597. def defaults_write_form(self, factor=None, fl_units=None, source_dict=None):
  2598. """
  2599. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2600. self.defaults dictionary.
  2601. :param factor: will apply a factor to the values that written in the GUI elements
  2602. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2603. :param source_dict: the repository of options, usually is the self.defaults
  2604. :return: None
  2605. """
  2606. options_storage = self.defaults if source_dict is None else source_dict
  2607. for option in options_storage:
  2608. if source_dict:
  2609. self.defaults_write_form_field(option, factor=factor, units=fl_units, defaults_dict=source_dict)
  2610. else:
  2611. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2612. # try:
  2613. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2614. # except KeyError:
  2615. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2616. # pass
  2617. def defaults_write_form_field(self, field, factor=None, units=None, defaults_dict=None):
  2618. """
  2619. Basically it is the worker in the self.defaults_write_form()
  2620. :param field: the GUI element in Preferences GUI to be updated
  2621. :param factor: factor to be applied to the field parameter
  2622. :param units: current FLatCAM measuring units
  2623. :param defaults_dict: the defaults storage
  2624. :return: None, it updates GUI elements
  2625. """
  2626. def_dict = self.defaults if defaults_dict is None else defaults_dict
  2627. try:
  2628. if factor is None:
  2629. if units is None:
  2630. self.defaults_form_fields[field].set_value(def_dict[field])
  2631. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2632. self.defaults_form_fields[field].set_value(def_dict[field])
  2633. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2634. self.defaults_form_fields[field].set_value(def_dict[field])
  2635. else:
  2636. if units is None:
  2637. self.defaults_form_fields[field].set_value(def_dict[field] * factor)
  2638. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2639. self.defaults_form_fields[field].set_value((def_dict[field] * factor))
  2640. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2641. self.defaults_form_fields[field].set_value((def_dict[field] * factor))
  2642. except KeyError:
  2643. pass
  2644. except AttributeError:
  2645. log.debug(field)
  2646. def clear_pool(self):
  2647. """
  2648. Clear the multiprocessing pool and calls garbage collector.
  2649. :return: None
  2650. """
  2651. self.pool.close()
  2652. self.pool = Pool()
  2653. self.pool_recreated.emit(self.pool)
  2654. gc.collect()
  2655. def install_tools(self):
  2656. """
  2657. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2658. Instantiation of the Tools classes.
  2659. The order that the tools are installed is important as they can depend on each other install position.
  2660. :return: None
  2661. """
  2662. self.distance_tool = Distance(self)
  2663. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  2664. before=self.ui.menueditorigin,
  2665. separator=False)
  2666. self.distance_min_tool = DistanceMin(self)
  2667. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  2668. pos=self.ui.menuedit,
  2669. before=self.ui.menueditorigin,
  2670. separator=True)
  2671. self.dblsidedtool = DblSidedTool(self)
  2672. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  2673. self.cal_exc_tool = ToolCalibration(self)
  2674. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  2675. before=self.dblsidedtool.menuAction,
  2676. separator=False)
  2677. self.align_objects_tool = AlignObjects(self)
  2678. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  2679. self.edrills_tool = ToolExtractDrills(self)
  2680. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  2681. self.panelize_tool = Panelize(self)
  2682. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  2683. self.film_tool = Film(self)
  2684. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  2685. self.paste_tool = SolderPaste(self)
  2686. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  2687. self.calculator_tool = ToolCalculator(self)
  2688. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  2689. self.sub_tool = ToolSub(self)
  2690. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  2691. pos=self.ui.menutool, separator=True)
  2692. self.rules_tool = RulesCheck(self)
  2693. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  2694. pos=self.ui.menutool, separator=False)
  2695. self.optimal_tool = ToolOptimal(self)
  2696. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  2697. pos=self.ui.menutool, separator=True)
  2698. self.move_tool = ToolMove(self)
  2699. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  2700. before=self.ui.menueditorigin, separator=True)
  2701. self.cutout_tool = CutOut(self)
  2702. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  2703. before=self.sub_tool.menuAction)
  2704. self.ncclear_tool = NonCopperClear(self)
  2705. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  2706. before=self.sub_tool.menuAction, separator=True)
  2707. self.paint_tool = ToolPaint(self)
  2708. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  2709. before=self.sub_tool.menuAction, separator=True)
  2710. self.copper_thieving_tool = ToolCopperThieving(self)
  2711. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  2712. pos=self.ui.menutool)
  2713. self.fiducial_tool = ToolFiducials(self)
  2714. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  2715. pos=self.ui.menutool)
  2716. self.qrcode_tool = QRCode(self)
  2717. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  2718. pos=self.ui.menutool)
  2719. self.punch_tool = ToolPunchGerber(self)
  2720. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  2721. self.transform_tool = ToolTransform(self)
  2722. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  2723. pos=self.ui.menuoptions, separator=True)
  2724. self.properties_tool = Properties(self)
  2725. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  2726. pos=self.ui.menuoptions)
  2727. self.pdf_tool = ToolPDF(self)
  2728. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  2729. pos=self.ui.menufileimport,
  2730. separator=True)
  2731. self.image_tool = ToolImage(self)
  2732. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  2733. pos=self.ui.menufileimport,
  2734. separator=True)
  2735. self.pcb_wizard_tool = PcbWizard(self)
  2736. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  2737. pos=self.ui.menufileimport)
  2738. self.log.debug("Tools are installed.")
  2739. def remove_tools(self):
  2740. """
  2741. Will remove all the actions in the Tool menu.
  2742. :return: None
  2743. """
  2744. for act in self.ui.menutool.actions():
  2745. self.ui.menutool.removeAction(act)
  2746. def init_tools(self):
  2747. """
  2748. Initialize the Tool tab in the notebook side of the central widget.
  2749. Remove the actions in the Tools menu.
  2750. Instantiate again the FlatCAM tools (plugins).
  2751. All this is required when changing the layout: standard, compact etc.
  2752. :return: None
  2753. """
  2754. log.debug("init_tools()")
  2755. # delete the data currently in the Tools Tab and the Tab itself
  2756. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2757. if widget is not None:
  2758. widget.deleteLater()
  2759. self.ui.notebook.removeTab(2)
  2760. # rebuild the Tools Tab
  2761. self.ui.tool_tab = QtWidgets.QWidget()
  2762. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2763. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2764. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2765. self.ui.tool_scroll_area = VerticalScrollArea()
  2766. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2767. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2768. # first remove all of them
  2769. self.remove_tools()
  2770. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2771. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  2772. '&Command Line\tS')
  2773. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2774. # third install all of them
  2775. try:
  2776. self.install_tools()
  2777. except AttributeError:
  2778. pass
  2779. self.log.debug("Tools are initialized.")
  2780. # def parse_system_fonts(self):
  2781. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2782. # 'params': []})
  2783. def connect_toolbar_signals(self):
  2784. """
  2785. Reconnect the signals to the actions in the toolbar.
  2786. This has to be done each time after the FlatCAM tools are removed/installed.
  2787. :return: None
  2788. """
  2789. # Toolbar
  2790. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2791. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2792. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2793. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2794. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2795. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2796. self.ui.replot_btn.triggered.connect(self.plot_all)
  2797. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2798. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2799. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2800. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2801. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2802. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2803. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2804. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2805. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  2806. self.ui.delete_btn.triggered.connect(self.on_delete)
  2807. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2808. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2809. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2810. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  2811. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2812. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  2813. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2814. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2815. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2816. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2817. # Tools Toolbar Signals
  2818. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2819. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  2820. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  2821. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  2822. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2823. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2824. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2825. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2826. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2827. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2828. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2829. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2830. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2831. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2832. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2833. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  2834. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  2835. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  2836. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  2837. def object2editor(self):
  2838. """
  2839. Send the current Geometry or Excellon object (if any) into the it's editor.
  2840. :return: None
  2841. """
  2842. self.report_usage("object2editor()")
  2843. # disable the objects menu as it may interfere with the Editors
  2844. self.ui.menuobjects.setDisabled(True)
  2845. edited_object = self.collection.get_active()
  2846. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2847. isinstance(edited_object, FlatCAMExcellon):
  2848. pass
  2849. else:
  2850. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  2851. return
  2852. if isinstance(edited_object, FlatCAMGeometry):
  2853. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2854. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2855. # we set the notebook to hidden
  2856. # self.ui.splitter.setSizes([0, 1])
  2857. if edited_object.multigeo is True:
  2858. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  2859. if len(sel_rows) > 1:
  2860. self.inform.emit('[WARNING_NOTCL] %s' %
  2861. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  2862. "is not possible.\n"
  2863. "Edit only one geometry at a time."))
  2864. # determine the tool dia of the selected tool
  2865. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  2866. # now find the key in the edited_object.tools that has this tooldia
  2867. multi_tool = 1
  2868. for tool in edited_object.tools:
  2869. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2870. multi_tool = tool
  2871. break
  2872. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2873. else:
  2874. self.geo_editor.edit_fcgeometry(edited_object)
  2875. # set call source to the Editor we go into
  2876. self.call_source = 'geo_editor'
  2877. elif isinstance(edited_object, FlatCAMExcellon):
  2878. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2879. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2880. if self.ui.splitter.sizes()[0] == 0:
  2881. self.ui.splitter.setSizes([1, 1])
  2882. self.exc_editor.edit_fcexcellon(edited_object)
  2883. # set call source to the Editor we go into
  2884. self.call_source = 'exc_editor'
  2885. elif isinstance(edited_object, FlatCAMGerber):
  2886. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2887. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2888. if self.ui.splitter.sizes()[0] == 0:
  2889. self.ui.splitter.setSizes([1, 1])
  2890. self.grb_editor.edit_fcgerber(edited_object)
  2891. # set call source to the Editor we go into
  2892. self.call_source = 'grb_editor'
  2893. # reset the following variables so the UI is built again after edit
  2894. edited_object.ui_build = False
  2895. edited_object.build_aperture_storage = False
  2896. # make sure that we can't select another object while in Editor Mode:
  2897. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2898. self.ui.project_frame.setDisabled(True)
  2899. # delete any selection shape that might be active as they are not relevant in Editor
  2900. self.delete_selection_shape()
  2901. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2902. self.ui.plot_tab_area.protectTab(0)
  2903. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  2904. self.should_we_save = True
  2905. def editor2object(self, cleanup=None):
  2906. """
  2907. Transfers the Geometry or Excellon from it's editor to the current object.
  2908. :return: None
  2909. """
  2910. self.report_usage("editor2object()")
  2911. # re-enable the objects menu that was disabled on entry in Editor mode
  2912. self.ui.menuobjects.setDisabled(False)
  2913. # do not update a geometry or excellon object unless it comes out of an editor
  2914. if self.call_source != 'app':
  2915. edited_obj = self.collection.get_active()
  2916. if cleanup is None:
  2917. msgbox = QtWidgets.QMessageBox()
  2918. msgbox.setText(_("Do you want to save the edited object?"))
  2919. msgbox.setWindowTitle(_("Close Editor"))
  2920. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2921. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2922. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2923. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2924. msgbox.setDefaultButton(bt_yes)
  2925. msgbox.exec_()
  2926. response = msgbox.clickedButton()
  2927. if response == bt_yes:
  2928. # clean the Tools Tab
  2929. self.ui.tool_scroll_area.takeWidget()
  2930. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2931. self.ui.notebook.setTabText(2, "Tool")
  2932. if isinstance(edited_obj, FlatCAMGeometry):
  2933. obj_type = "Geometry"
  2934. if cleanup is None:
  2935. self.geo_editor.update_fcgeometry(edited_obj)
  2936. # self.geo_editor.update_options(edited_obj)
  2937. self.geo_editor.deactivate()
  2938. # restore GUI to the Selected TAB
  2939. # Remove anything else in the GUI
  2940. self.ui.tool_scroll_area.takeWidget()
  2941. # update the geo object options so it is including the bounding box values
  2942. try:
  2943. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2944. edited_obj.options['xmin'] = xmin
  2945. edited_obj.options['ymin'] = ymin
  2946. edited_obj.options['xmax'] = xmax
  2947. edited_obj.options['ymax'] = ymax
  2948. except AttributeError as e:
  2949. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  2950. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2951. edited_obj.build_ui()
  2952. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2953. elif isinstance(edited_obj, FlatCAMGerber):
  2954. obj_type = "Gerber"
  2955. if cleanup is None:
  2956. self.grb_editor.update_fcgerber()
  2957. self.grb_editor.update_options(edited_obj)
  2958. self.grb_editor.deactivate_grb_editor()
  2959. # delete the old object (the source object) if it was an empty one
  2960. try:
  2961. if len(edited_obj.solid_geometry) == 0:
  2962. old_name = edited_obj.options['name']
  2963. self.collection.set_active(old_name)
  2964. self.collection.delete_active()
  2965. except TypeError:
  2966. # if the solid_geometry is a single Polygon the len() will not work
  2967. # in any case, falling here means that we have something in the solid_geometry, even if only
  2968. # a single Polygon, therefore we pass this
  2969. pass
  2970. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2971. # restore GUI to the Selected TAB
  2972. # Remove anything else in the GUI
  2973. self.ui.selected_scroll_area.takeWidget()
  2974. elif isinstance(edited_obj, FlatCAMExcellon):
  2975. obj_type = "Excellon"
  2976. if cleanup is None:
  2977. self.exc_editor.update_fcexcellon(edited_obj)
  2978. # self.exc_editor.update_options(edited_obj)
  2979. self.exc_editor.deactivate()
  2980. # restore GUI to the Selected TAB
  2981. # Remove anything else in the GUI
  2982. self.ui.tool_scroll_area.takeWidget()
  2983. # delete the old object (the source object) if it was an empty one
  2984. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2985. old_name = edited_obj.options['name']
  2986. self.collection.delete_by_name(name=old_name)
  2987. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2988. else:
  2989. self.inform.emit('[WARNING_NOTCL] %s' %
  2990. _("Select a Gerber, Geometry or Excellon Object to update."))
  2991. return
  2992. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  2993. elif response == bt_no:
  2994. # clean the Tools Tab
  2995. self.ui.tool_scroll_area.takeWidget()
  2996. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2997. self.ui.notebook.setTabText(2, "Tool")
  2998. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  2999. if isinstance(edited_obj, FlatCAMGeometry):
  3000. self.geo_editor.deactivate()
  3001. edited_obj.build_ui()
  3002. elif isinstance(edited_obj, FlatCAMGerber):
  3003. self.grb_editor.deactivate_grb_editor()
  3004. edited_obj.build_ui()
  3005. elif isinstance(edited_obj, FlatCAMExcellon):
  3006. self.exc_editor.deactivate()
  3007. edited_obj.build_ui()
  3008. else:
  3009. self.inform.emit('[WARNING_NOTCL] %s' %
  3010. _("Select a Gerber, Geometry or Excellon Object to update."))
  3011. return
  3012. elif response == bt_cancel:
  3013. return
  3014. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  3015. # edited_obj.build_ui()
  3016. # Switch notebook to Selected page
  3017. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3018. else:
  3019. if isinstance(edited_obj, FlatCAMGeometry):
  3020. self.geo_editor.deactivate()
  3021. elif isinstance(edited_obj, FlatCAMGerber):
  3022. self.grb_editor.deactivate_grb_editor()
  3023. elif isinstance(edited_obj, FlatCAMExcellon):
  3024. self.exc_editor.deactivate()
  3025. else:
  3026. self.inform.emit('[WARNING_NOTCL] %s' %
  3027. _("Select a Gerber, Geometry or Excellon Object to update."))
  3028. return
  3029. # if notebook is hidden we show it
  3030. if self.ui.splitter.sizes()[0] == 0:
  3031. self.ui.splitter.setSizes([1, 1])
  3032. # restore the call_source to app
  3033. self.call_source = 'app'
  3034. edited_obj.plot()
  3035. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  3036. self.ui.plot_tab_area.protectTab(0)
  3037. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  3038. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  3039. self.ui.project_frame.setDisabled(False)
  3040. def get_last_folder(self):
  3041. """
  3042. Get the folder path from where the last file was opened.
  3043. :return: String, last opened folder path
  3044. """
  3045. return self.defaults["global_last_folder"]
  3046. def get_last_save_folder(self):
  3047. """
  3048. Get the folder path from where the last file was saved.
  3049. :return: String, last saved folder path
  3050. """
  3051. loc = self.defaults["global_last_save_folder"]
  3052. if loc is None:
  3053. loc = self.defaults["global_last_folder"]
  3054. if loc is None:
  3055. loc = os.path.dirname(__file__)
  3056. return loc
  3057. def report_usage(self, resource):
  3058. """
  3059. Increments usage counter for the given resource
  3060. in self.defaults['global_stats'].
  3061. :param resource: Name of the resource.
  3062. :return: None
  3063. """
  3064. if resource in self.defaults['global_stats']:
  3065. self.defaults['global_stats'][resource] += 1
  3066. else:
  3067. self.defaults['global_stats'][resource] = 1
  3068. def init_tcl(self):
  3069. """
  3070. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  3071. :return: None
  3072. """
  3073. if hasattr(self, 'tcl') and self.tcl is not None:
  3074. # self.tcl = None
  3075. # TODO we need to clean non default variables and procedures here
  3076. # new object cannot be used here as it will not remember values created for next passes,
  3077. # because tcl was execudted in old instance of TCL
  3078. pass
  3079. else:
  3080. self.tcl = tk.Tcl()
  3081. self.setup_shell()
  3082. self.log.debug("TCL Shell has been initialized.")
  3083. # TODO: This shouldn't be here.
  3084. class TclErrorException(Exception):
  3085. """
  3086. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  3087. """
  3088. pass
  3089. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  3090. """
  3091. Shows a message on the FlatCAM Shell
  3092. :param msg: Message to display.
  3093. :param show: Opens the shell.
  3094. :param error: Shows the message as an error.
  3095. :param warning: Shows the message as an warning.
  3096. :param success: Shows the message as an success.
  3097. :param selected: Indicate that something was selected on canvas
  3098. :return: None
  3099. """
  3100. if show:
  3101. self.ui.shell_dock.show()
  3102. try:
  3103. if error:
  3104. self.shell.append_error(msg + "\n")
  3105. elif warning:
  3106. self.shell.append_warning(msg + "\n")
  3107. elif success:
  3108. self.shell.append_success(msg + "\n")
  3109. elif selected:
  3110. self.shell.append_selected(msg + "\n")
  3111. else:
  3112. self.shell.append_output(msg + "\n")
  3113. except AttributeError:
  3114. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  3115. def raise_tcl_unknown_error(self, unknownException):
  3116. """
  3117. Raise exception if is different type than TclErrorException
  3118. this is here mainly to show unknown errors inside TCL shell console.
  3119. :param unknownException:
  3120. :return:
  3121. """
  3122. if not isinstance(unknownException, self.TclErrorException):
  3123. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  3124. else:
  3125. raise unknownException
  3126. def display_tcl_error(self, error, error_info=None):
  3127. """
  3128. Escape bracket [ with '\' otherwise there is error
  3129. "ERROR: missing close-bracket" instead of real error
  3130. :param error: it may be text or exception
  3131. :param error_info: Some informations about the error
  3132. :return: None
  3133. """
  3134. if isinstance(error, Exception):
  3135. exc_type, exc_value, exc_traceback = error_info
  3136. if not isinstance(error, self.TclErrorException):
  3137. show_trace = 1
  3138. else:
  3139. show_trace = int(self.defaults['global_verbose_error_level'])
  3140. if show_trace > 0:
  3141. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  3142. trc_formated = []
  3143. for a in reversed(trc):
  3144. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  3145. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  3146. else:
  3147. text = "%s" % error
  3148. else:
  3149. text = error
  3150. text = text.replace('[', '\\[').replace('"', '\\"')
  3151. self.tcl.eval('return -code error "%s"' % text)
  3152. def raise_tcl_error(self, text):
  3153. """
  3154. This method pass exception from python into TCL as error, so we get stacktrace and reason
  3155. :param text: text of error
  3156. :return: raise exception
  3157. """
  3158. self.display_tcl_error(text)
  3159. raise self.TclErrorException(text)
  3160. def exec_command(self, text, no_echo=False):
  3161. """
  3162. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3163. Also handles execution in separated threads
  3164. :param text: FlatCAM TclCommand with parameters
  3165. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3166. will create crashes of the _Expandable_Edit widget
  3167. :return: output if there was any
  3168. """
  3169. self.report_usage('exec_command')
  3170. result = self.exec_command_test(text, False, no_echo=no_echo)
  3171. # MS: added this method call so the geometry is updated once the TCL command is executed
  3172. # if no_plot is None:
  3173. # self.plot_all()
  3174. return result
  3175. def exec_command_test(self, text, reraise=True, no_echo=False):
  3176. """
  3177. Same as exec_command(...) with additional control over exceptions.
  3178. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3179. :param text: Input command
  3180. :param reraise: Re-raise TclError exceptions in Python (mostly for unittests).
  3181. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3182. will create crashes of the _Expandable_Edit widget
  3183. :return: Output from the command
  3184. """
  3185. tcl_command_string = str(text)
  3186. try:
  3187. if no_echo is False:
  3188. self.shell.open_processing() # Disables input box.
  3189. result = self.tcl.eval(str(tcl_command_string))
  3190. if result != 'None' and no_echo is False:
  3191. self.shell.append_output(result + '\n')
  3192. except tk.TclError as e:
  3193. # This will display more precise answer if something in TCL shell fails
  3194. result = self.tcl.eval("set errorInfo")
  3195. self.log.error("Exec command Exception: %s" % (result + '\n'))
  3196. if no_echo is False:
  3197. self.shell.append_error('ERROR: ' + result + '\n')
  3198. # Show error in console and just return or in test raise exception
  3199. if reraise:
  3200. raise e
  3201. finally:
  3202. if no_echo is False:
  3203. self.shell.close_processing()
  3204. pass
  3205. return result
  3206. # """
  3207. # Code below is unsused. Saved for later.
  3208. # """
  3209. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  3210. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  3211. # self.log.debug(parts)
  3212. # try:
  3213. # if parts[0] not in commands:
  3214. # self.shell.append_error("Unknown command\n")
  3215. # return
  3216. #
  3217. # #import inspect
  3218. # #inspect.getargspec(someMethod)
  3219. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  3220. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  3221. # self.shell.append_error(
  3222. # "Command %s takes %d arguments. %d given.\n" %
  3223. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  3224. # )
  3225. # return
  3226. #
  3227. # cmdfcn = commands[parts[0]]["fcn"]
  3228. # cmdconv = commands[parts[0]]["converters"]
  3229. # if len(parts) - 1 > 0:
  3230. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  3231. # else:
  3232. # retval = cmdfcn()
  3233. # retfcn = commands[parts[0]]["retfcn"]
  3234. # if retval and retfcn(retval):
  3235. # self.shell.append_output(retfcn(retval) + "\n")
  3236. #
  3237. # except Exception as e:
  3238. # #self.shell.append_error(''.join(traceback.format_exc()))
  3239. # #self.shell.append_error("?\n")
  3240. # self.shell.append_error(str(e) + "\n")
  3241. def info(self, msg):
  3242. """
  3243. Informs the user. Normally on the status bar, optionally
  3244. also on the shell.
  3245. :param msg: Text to write.
  3246. :return: None
  3247. """
  3248. # Type of message in brackets at the beginning of the message.
  3249. match = re.search("\[([^\]]+)\](.*)", msg)
  3250. if match:
  3251. level = match.group(1)
  3252. msg_ = match.group(2)
  3253. self.ui.fcinfo.set_status(str(msg_), level=level)
  3254. if level.lower() == "error":
  3255. self.shell_message(msg, error=True, show=True)
  3256. elif level.lower() == "warning":
  3257. self.shell_message(msg, warning=True, show=True)
  3258. elif level.lower() == "error_notcl":
  3259. self.shell_message(msg, error=True, show=False)
  3260. elif level.lower() == "warning_notcl":
  3261. self.shell_message(msg, warning=True, show=False)
  3262. elif level.lower() == "success":
  3263. self.shell_message(msg, success=True, show=False)
  3264. elif level.lower() == "selected":
  3265. self.shell_message(msg, selected=True, show=False)
  3266. else:
  3267. self.shell_message(msg, show=False)
  3268. else:
  3269. self.ui.fcinfo.set_status(str(msg), level="info")
  3270. # make sure that if the message is to clear the infobar with a space
  3271. # is not printed over and over on the shell
  3272. if msg != '':
  3273. self.shell_message(msg)
  3274. def restore_toolbar_view(self):
  3275. """
  3276. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3277. was saved in the defaults dictionary.
  3278. :return: None
  3279. """
  3280. tb = self.defaults["global_toolbar_view"]
  3281. if tb & 1:
  3282. self.ui.toolbarfile.setVisible(True)
  3283. else:
  3284. self.ui.toolbarfile.setVisible(False)
  3285. if tb & 2:
  3286. self.ui.toolbargeo.setVisible(True)
  3287. else:
  3288. self.ui.toolbargeo.setVisible(False)
  3289. if tb & 4:
  3290. self.ui.toolbarview.setVisible(True)
  3291. else:
  3292. self.ui.toolbarview.setVisible(False)
  3293. if tb & 8:
  3294. self.ui.toolbartools.setVisible(True)
  3295. else:
  3296. self.ui.toolbartools.setVisible(False)
  3297. if tb & 16:
  3298. self.ui.exc_edit_toolbar.setVisible(True)
  3299. else:
  3300. self.ui.exc_edit_toolbar.setVisible(False)
  3301. if tb & 32:
  3302. self.ui.geo_edit_toolbar.setVisible(True)
  3303. else:
  3304. self.ui.geo_edit_toolbar.setVisible(False)
  3305. if tb & 64:
  3306. self.ui.grb_edit_toolbar.setVisible(True)
  3307. else:
  3308. self.ui.grb_edit_toolbar.setVisible(False)
  3309. if tb & 128:
  3310. self.ui.snap_toolbar.setVisible(True)
  3311. else:
  3312. self.ui.snap_toolbar.setVisible(False)
  3313. if tb & 256:
  3314. self.ui.toolbarshell.setVisible(True)
  3315. else:
  3316. self.ui.toolbarshell.setVisible(False)
  3317. def load_defaults(self, filename):
  3318. """
  3319. Loads the aplication's default settings from current_defaults.FlatConfig into
  3320. ``self.defaults``.
  3321. :return: None
  3322. """
  3323. try:
  3324. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3325. options = f.read()
  3326. f.close()
  3327. except IOError:
  3328. self.log.error("Could not load defaults file.")
  3329. self.inform.emit('[ERROR] %s' % _("Could not load defaults file."))
  3330. # in case the defaults file can't be loaded, show all toolbars
  3331. self.defaults["global_toolbar_view"] = 511
  3332. return
  3333. try:
  3334. defaults = json.loads(options)
  3335. except Exception:
  3336. # in case the defaults file can't be loaded, show all toolbars
  3337. self.defaults["global_toolbar_view"] = 511
  3338. e = sys.exc_info()[0]
  3339. App.log.error(str(e))
  3340. self.inform.emit('[ERROR] %s' % _("Failed to parse defaults file."))
  3341. return
  3342. if defaults:
  3343. if 'version' not in defaults or defaults['version'] != self.defaults['version']:
  3344. for k, v in defaults.items():
  3345. if k in self.defaults and k != 'version':
  3346. self.defaults[k] = v
  3347. # delete old factory defaults
  3348. try:
  3349. fact_def_file_path = os.path.join(self.data_path, 'factory_defaults.FlatConfig')
  3350. os.chmod(fact_def_file_path, stat.S_IRWXO | stat.S_IWRITE | stat.S_IWGRP)
  3351. os.remove(fact_def_file_path)
  3352. # recreate a new factory defaults file and save the factory defaults data into it
  3353. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  3354. json.dump(self.defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3355. f_f_def_s.close()
  3356. # and then make the factory_defaults.FlatConfig file read_only
  3357. # so it can't be modified after creation.
  3358. os.chmod(fact_def_file_path, S_IREAD | S_IRGRP | S_IROTH)
  3359. except Exception as e:
  3360. log.debug("App.load_defaults() -> deleting old factory defaults file -> %s" % str(e))
  3361. self.old_defaults_found = True
  3362. else:
  3363. self.old_defaults_found = False
  3364. self.defaults.update(defaults)
  3365. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3366. def on_restore_defaults_preferences(self):
  3367. """
  3368. Loads the application's factory default settings from factory_defaults.FlatConfig into
  3369. ``self.defaults``.
  3370. :return: None
  3371. """
  3372. App.log.debug("App.on_restore_defaults_preferences()")
  3373. filename = self.data_path + '/factory_defaults.FlatConfig'
  3374. if filename == "":
  3375. self.inform.emit('[WARNING_NOTCL] %s' % _("Preferences default restore was cancelled."))
  3376. else:
  3377. try:
  3378. f = open(filename)
  3379. options = f.read()
  3380. f.close()
  3381. except IOError:
  3382. self.log.error("Could not load factory defaults file.")
  3383. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load factory defaults file."))
  3384. return
  3385. try:
  3386. defaults_from_file = json.loads(options)
  3387. except Exception:
  3388. e = sys.exc_info()[0]
  3389. App.log.error(str(e))
  3390. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse factory defaults file."))
  3391. return
  3392. self.defaults.update(defaults_from_file)
  3393. # update the dict that is used to restore the values in the defaults form if Cancel is clicked in the
  3394. # Preferences window
  3395. self.current_defaults.update(defaults_from_file)
  3396. self.on_preferences_edited()
  3397. self.inform.emit('[success] %s' % _("Preferences default values are restored."))
  3398. def on_import_preferences(self):
  3399. """
  3400. Loads the application default settings from a saved file into
  3401. ``self.defaults`` dictionary.
  3402. :return: None
  3403. """
  3404. self.report_usage("on_import_preferences")
  3405. App.log.debug("App.on_import_preferences()")
  3406. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3407. try:
  3408. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3409. directory=self.data_path,
  3410. filter=filter_)
  3411. except TypeError:
  3412. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3413. filter=filter_)
  3414. filename = str(filename)
  3415. if filename == "":
  3416. self.inform.emit('[WARNING_NOTCL] %s' % _("FlatCAM preferences import cancelled."))
  3417. else:
  3418. try:
  3419. f = open(filename)
  3420. options = f.read()
  3421. f.close()
  3422. except IOError:
  3423. self.log.error("Could not load defaults file.")
  3424. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load defaults file."))
  3425. return
  3426. try:
  3427. defaults_from_file = json.loads(options)
  3428. except Exception:
  3429. e = sys.exc_info()[0]
  3430. App.log.error(str(e))
  3431. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse defaults file."))
  3432. return
  3433. self.defaults.update(defaults_from_file)
  3434. # update the dict that is used to restore the values in the defaults form if Cancel is clicked in the
  3435. # Preferences window
  3436. self.current_defaults.update(defaults_from_file)
  3437. self.on_preferences_edited()
  3438. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  3439. def on_export_preferences(self):
  3440. """
  3441. Save the defaults dictionary to a file.
  3442. :return: None
  3443. """
  3444. self.report_usage("on_export_preferences")
  3445. App.log.debug("on_export_preferences()")
  3446. defaults_file_content = None
  3447. self.date = str(datetime.today()).rpartition('.')[0]
  3448. self.date = ''.join(c for c in self.date if c not in ':-')
  3449. self.date = self.date.replace(' ', '_')
  3450. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3451. try:
  3452. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3453. caption=_("Export FlatCAM Preferences"),
  3454. directory=self.data_path + '/preferences_' + self.date,
  3455. filter=filter__
  3456. )
  3457. except TypeError:
  3458. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3459. filter=filter__)
  3460. filename = str(filename)
  3461. defaults_from_file = {}
  3462. if filename == "":
  3463. self.inform.emit('[WARNING_NOTCL] %s' % _("FlatCAM preferences export cancelled."))
  3464. return
  3465. else:
  3466. try:
  3467. f = open(filename, 'w')
  3468. defaults_file_content = f.read()
  3469. f.close()
  3470. except PermissionError:
  3471. self.inform.emit('[WARNING] %s' %
  3472. _("Permission denied, saving not possible.\n"
  3473. "Most likely another app is holding the file open and not accessible."))
  3474. return
  3475. except IOError:
  3476. App.log.debug('Creating a new preferences file ...')
  3477. f = open(filename, 'w')
  3478. json.dump({}, f)
  3479. f.close()
  3480. except Exception:
  3481. e = sys.exc_info()[0]
  3482. App.log.error("Could not load defaults file.")
  3483. App.log.error(str(e))
  3484. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load preferences file."))
  3485. return
  3486. try:
  3487. defaults_from_file = json.loads(defaults_file_content)
  3488. except Exception:
  3489. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3490. # Update options
  3491. self.defaults_read_form()
  3492. defaults_from_file.update(self.defaults)
  3493. self.propagate_defaults(silent=True)
  3494. # Save update options
  3495. try:
  3496. f = open(filename, "w")
  3497. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3498. f.close()
  3499. except Exception:
  3500. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  3501. return
  3502. if self.defaults["global_open_style"] is False:
  3503. self.file_opened.emit("preferences", filename)
  3504. self.file_saved.emit("preferences", filename)
  3505. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  3506. def save_geometry(self, x, y, width, height, notebook_width):
  3507. """
  3508. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3509. launch of the application.
  3510. :param x: X position of the main window
  3511. :param y: Y position of the main window
  3512. :param width: width of the main window
  3513. :param height: height of the main window
  3514. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3515. :return: None
  3516. """
  3517. self.defaults["global_def_win_x"] = x
  3518. self.defaults["global_def_win_y"] = y
  3519. self.defaults["global_def_win_w"] = width
  3520. self.defaults["global_def_win_h"] = height
  3521. self.defaults["global_def_notebook_width"] = notebook_width
  3522. self.save_defaults()
  3523. def restore_main_win_geom(self):
  3524. try:
  3525. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3526. self.defaults["global_def_win_y"],
  3527. self.defaults["global_def_win_w"],
  3528. self.defaults["global_def_win_h"])
  3529. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3530. except KeyError as e:
  3531. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3532. def message_dialog(self, title, message, kind="info"):
  3533. """
  3534. Builds and show a custom QMessageBox to be used in FlatCAM.
  3535. :param title: title of the QMessageBox
  3536. :param message: message to be displayed
  3537. :param kind: type of QMessageBox; will display a specific icon.
  3538. :return:
  3539. """
  3540. icon = {"info": QtWidgets.QMessageBox.Information,
  3541. "warning": QtWidgets.QMessageBox.Warning,
  3542. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3543. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3544. dlg.setText(message)
  3545. dlg.exec_()
  3546. def register_recent(self, kind, filename):
  3547. """
  3548. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3549. dictionary.
  3550. :param kind: type of file that was opened
  3551. :param filename: the path and file name for the file that was opened
  3552. :return:
  3553. """
  3554. self.log.debug("register_recent()")
  3555. self.log.debug(" %s" % kind)
  3556. self.log.debug(" %s" % filename)
  3557. record = {'kind': str(kind), 'filename': str(filename)}
  3558. if record in self.recent:
  3559. return
  3560. if record in self.recent_projects:
  3561. return
  3562. if record['kind'] == 'project':
  3563. self.recent_projects.insert(0, record)
  3564. else:
  3565. self.recent.insert(0, record)
  3566. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3567. self.recent.pop()
  3568. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3569. self.recent_projects.pop()
  3570. try:
  3571. f = open(self.data_path + '/recent.json', 'w')
  3572. except IOError:
  3573. App.log.error("Failed to open recent items file for writing.")
  3574. self.inform.emit('[ERROR_NOTCL] %s' %
  3575. _('Failed to open recent files file for writing.'))
  3576. return
  3577. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3578. f.close()
  3579. try:
  3580. fp = open(self.data_path + '/recent_projects.json', 'w')
  3581. except IOError:
  3582. App.log.error("Failed to open recent items file for writing.")
  3583. self.inform.emit('[ERROR_NOTCL] %s' %
  3584. _('Failed to open recent projects file for writing.'))
  3585. return
  3586. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3587. fp.close()
  3588. # Re-build the recent items menu
  3589. self.setup_recent_items()
  3590. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3591. """
  3592. Creates a new specialized FlatCAMObj and attaches it to the application,
  3593. this is, updates the GUI accordingly, any other records and plots it.
  3594. This method is thread-safe.
  3595. Notes:
  3596. * If the name is in use, the self.collection will modify it
  3597. when appending it to the collection. There is no need to handle
  3598. name conflicts here.
  3599. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3600. :type kind: str
  3601. :param name: Name for the object.
  3602. :type name: str
  3603. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3604. The function is called with 2 parameters: the new object and the App instance.
  3605. :type initialize: function
  3606. :param active:
  3607. :param fit:
  3608. :param plot: If to plot the resulting object
  3609. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3610. self.colleaction
  3611. :return: None
  3612. :rtype: None
  3613. """
  3614. App.log.debug("new_object()")
  3615. obj_plot = plot
  3616. obj_autoselected = autoselected
  3617. t0 = time.time() # Debug
  3618. # ## Create object
  3619. classdict = {
  3620. "gerber": FlatCAMGerber,
  3621. "excellon": FlatCAMExcellon,
  3622. "cncjob": FlatCAMCNCjob,
  3623. "geometry": FlatCAMGeometry,
  3624. "script": FlatCAMScript,
  3625. "document": FlatCAMDocument
  3626. }
  3627. App.log.debug("Calling object constructor...")
  3628. # Object creation/instantiation
  3629. obj = classdict[kind](name)
  3630. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3631. # IMPORTANT
  3632. # The key names in defaults and options dictionary's are not random:
  3633. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3634. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  3635. # copied to self.options. After that, below, depending on the type of
  3636. # object that is created, it will strip the name of the object and the underline (if the original key was
  3637. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3638. # "toolchange"
  3639. for option in self.options:
  3640. if option.find(kind + "_") == 0:
  3641. oname = option[len(kind) + 1:]
  3642. obj.options[oname] = self.options[option]
  3643. obj.isHovering = False
  3644. obj.notHovering = True
  3645. # Initialize as per user request
  3646. # User must take care to implement initialize
  3647. # in a thread-safe way as is is likely that we
  3648. # have been invoked in a separate thread.
  3649. t1 = time.time()
  3650. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3651. try:
  3652. return_value = initialize(obj, self)
  3653. except Exception as e:
  3654. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  3655. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3656. msg += traceback.format_exc()
  3657. self.inform.emit(msg)
  3658. return "fail"
  3659. t2 = time.time()
  3660. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3661. if return_value == 'fail':
  3662. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3663. return "fail"
  3664. # Check units and convert if necessary
  3665. # This condition CAN be true because initialize() can change obj.units
  3666. if self.options["units"].upper() != obj.units.upper():
  3667. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  3668. obj.convert_units(self.options["units"])
  3669. t3 = time.time()
  3670. self.log.debug("%f seconds converting units." % (t3 - t2))
  3671. # Create the bounding box for the object and then add the results to the obj.options
  3672. # But not for Scripts or for Documents
  3673. if kind != 'document' and kind != 'script':
  3674. try:
  3675. xmin, ymin, xmax, ymax = obj.bounds()
  3676. obj.options['xmin'] = xmin
  3677. obj.options['ymin'] = ymin
  3678. obj.options['xmax'] = xmax
  3679. obj.options['ymax'] = ymax
  3680. except Exception as e:
  3681. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  3682. return "fail"
  3683. try:
  3684. if kind == 'excellon':
  3685. obj.fill_color = self.defaults["excellon_plot_fill"]
  3686. obj.outline_color = self.defaults["excellon_plot_line"]
  3687. if kind == 'gerber':
  3688. obj.fill_color = self.defaults["gerber_plot_fill"]
  3689. obj.outline_color = self.defaults["gerber_plot_line"]
  3690. except Exception as e:
  3691. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  3692. # update the KeyWords list with the name of the file
  3693. self.myKeywords.append(obj.options['name'])
  3694. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3695. # Move the object to the main thread and let the app know that it is available.
  3696. obj.moveToThread(self.main_thread)
  3697. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3698. return obj
  3699. def new_excellon_object(self):
  3700. """
  3701. Creates a new, blank Excellon object.
  3702. :return: None
  3703. """
  3704. self.report_usage("new_excellon_object()")
  3705. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3706. def new_geometry_object(self):
  3707. """
  3708. Creates a new, blank and single-tool Geometry object.
  3709. :return: None
  3710. """
  3711. self.report_usage("new_geometry_object()")
  3712. def initialize(obj, app):
  3713. obj.multitool = False
  3714. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3715. def new_gerber_object(self):
  3716. """
  3717. Creates a new, blank Gerber object.
  3718. :return: None
  3719. """
  3720. self.report_usage("new_gerber_object()")
  3721. def initialize(grb_obj, app):
  3722. grb_obj.multitool = False
  3723. grb_obj.source_file = []
  3724. grb_obj.multigeo = False
  3725. grb_obj.follow = False
  3726. grb_obj.apertures = {}
  3727. grb_obj.solid_geometry = []
  3728. try:
  3729. grb_obj.options['xmin'] = 0
  3730. grb_obj.options['ymin'] = 0
  3731. grb_obj.options['xmax'] = 0
  3732. grb_obj.options['ymax'] = 0
  3733. except KeyError:
  3734. pass
  3735. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3736. def new_script_object(self, name=None, text=None):
  3737. """
  3738. Creates a new, blank TCL Script object.
  3739. :param name: a name for the new object
  3740. :param text: pass a source file to the newly created script to be loaded in it
  3741. :return: None
  3742. """
  3743. self.report_usage("new_script_object()")
  3744. if text is not None:
  3745. new_source_file = text
  3746. else:
  3747. commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  3748. "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n"\
  3749. "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  3750. "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n"\
  3751. "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  3752. "ListSys, MillDrills,\n"\
  3753. "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  3754. "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"\
  3755. "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  3756. "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  3757. "# SubtractRectangle, Version, WriteGCode\n"
  3758. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  3759. '# %s:\n' % _('TCL Tutorial is here') + \
  3760. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  3761. '# %s:\n' % _("FlatCAM commands list")
  3762. new_source_file += commands_list + '\n'
  3763. def initialize(obj, app):
  3764. obj.source_file = deepcopy(new_source_file)
  3765. if name is None:
  3766. outname = 'new_script'
  3767. else:
  3768. outname = name
  3769. self.new_object('script', outname, initialize, plot=False)
  3770. def new_document_object(self):
  3771. """
  3772. Creates a new, blank Document object.
  3773. :return: None
  3774. """
  3775. self.report_usage("new_document_object()")
  3776. def initialize(obj, app):
  3777. obj.source_file = ""
  3778. self.new_object('document', 'new_document', initialize, plot=False)
  3779. def on_object_created(self, obj, plot, auto_select):
  3780. """
  3781. Event callback for object creation.
  3782. It will add the new object to the collection. After that it will plot the object in a threaded way
  3783. :param obj: The newly created FlatCAM object.
  3784. :param plot: if the newly create object t obe plotted
  3785. :param auto_select: if the newly created object to be autoselected after creation
  3786. :return: None
  3787. """
  3788. t0 = time.time() # DEBUG
  3789. self.log.debug("on_object_created()")
  3790. # The Collection might change the name if there is a collision
  3791. self.collection.append(obj)
  3792. # after adding the object to the collection always update the list of objects that are in the collection
  3793. self.all_objects_list = self.collection.get_list()
  3794. # self.inform.emit('[selected] %s created & selected: %s' %
  3795. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3796. if obj.kind == 'gerber':
  3797. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3798. kind=obj.kind.capitalize(),
  3799. color='green',
  3800. name=str(obj.options['name']), tx=_("created/selected"))
  3801. )
  3802. elif obj.kind == 'excellon':
  3803. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3804. kind=obj.kind.capitalize(),
  3805. color='brown',
  3806. name=str(obj.options['name']), tx=_("created/selected"))
  3807. )
  3808. elif obj.kind == 'cncjob':
  3809. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3810. kind=obj.kind.capitalize(),
  3811. color='blue',
  3812. name=str(obj.options['name']), tx=_("created/selected"))
  3813. )
  3814. elif obj.kind == 'geometry':
  3815. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3816. kind=obj.kind.capitalize(),
  3817. color='red',
  3818. name=str(obj.options['name']), tx=_("created/selected"))
  3819. )
  3820. elif obj.kind == 'script':
  3821. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3822. kind=obj.kind.capitalize(),
  3823. color='orange',
  3824. name=str(obj.options['name']), tx=_("created/selected"))
  3825. )
  3826. elif obj.kind == 'document':
  3827. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3828. kind=obj.kind.capitalize(),
  3829. color='darkCyan',
  3830. name=str(obj.options['name']), tx=_("created/selected"))
  3831. )
  3832. # update the SHELL auto-completer model with the name of the new object
  3833. self.shell._edit.set_model_data(self.myKeywords)
  3834. if auto_select:
  3835. # select the just opened object but deselect the previous ones
  3836. self.collection.set_all_inactive()
  3837. self.collection.set_active(obj.options["name"])
  3838. else:
  3839. self.collection.set_all_inactive()
  3840. # here it is done the object plotting
  3841. def worker_task(t_obj):
  3842. with self.proc_container.new(_("Plotting")):
  3843. if isinstance(t_obj, FlatCAMCNCjob):
  3844. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3845. else:
  3846. t_obj.plot()
  3847. t1 = time.time() # DEBUG
  3848. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3849. self.object_plotted.emit(t_obj)
  3850. # Send to worker
  3851. # self.worker.add_task(worker_task, [self])
  3852. if plot is True:
  3853. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3854. def on_object_changed(self, obj):
  3855. """
  3856. Called whenever the geometry of the object was changed in some way.
  3857. This require the update of it's bounding values so it can be the selected on canvas.
  3858. Update the bounding box data from obj.options
  3859. :param obj: the object that was changed
  3860. :return: None
  3861. """
  3862. xmin, ymin, xmax, ymax = obj.bounds()
  3863. obj.options['xmin'] = xmin
  3864. obj.options['ymin'] = ymin
  3865. obj.options['xmax'] = xmax
  3866. obj.options['ymax'] = ymax
  3867. log.debug("Object changed, updating the bounding box data on self.options")
  3868. # delete the old selection shape
  3869. self.delete_selection_shape()
  3870. self.should_we_save = True
  3871. def on_object_plotted(self):
  3872. """
  3873. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3874. :return: None
  3875. """
  3876. self.on_zoom_fit(None)
  3877. def on_about(self):
  3878. """
  3879. Displays the "about" dialog found in the Menu --> Help.
  3880. :return: None
  3881. """
  3882. self.report_usage("on_about")
  3883. version = self.version
  3884. version_date = self.version_date
  3885. beta = self.beta
  3886. class AboutDialog(QtWidgets.QDialog):
  3887. def __init__(self, app, parent=None):
  3888. QtWidgets.QDialog.__init__(self, parent)
  3889. self.app = app
  3890. # Icon and title
  3891. self.setWindowIcon(parent.app_icon)
  3892. self.setWindowTitle(_("About FlatCAM"))
  3893. self.resize(600, 200)
  3894. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3895. # self.setStyleSheet(
  3896. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3897. # "background-attachment: fixed"
  3898. # )
  3899. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  3900. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3901. # palette = QtGui.QPalette()
  3902. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3903. # self.setPalette(palette)
  3904. logo = QtWidgets.QLabel()
  3905. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  3906. title = QtWidgets.QLabel(
  3907. "<font size=8><B>FlatCAM</B></font><BR>"
  3908. "{title}<BR>"
  3909. "<BR>"
  3910. "<BR>"
  3911. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3912. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3913. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3914. "<B>{issue}</B></a><BR>".format(
  3915. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3916. devel=_("Development"),
  3917. down=_("DOWNLOAD"),
  3918. issue=_("Issue tracker"))
  3919. )
  3920. title.setOpenExternalLinks(True)
  3921. closebtn = QtWidgets.QPushButton(_("Close"))
  3922. tab_widget = QtWidgets.QTabWidget()
  3923. description_label = QtWidgets.QLabel(
  3924. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3925. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3926. version=version,
  3927. beta=('BETA' if beta else ''),
  3928. date=version_date,
  3929. arch=platform.architecture()[0])
  3930. )
  3931. description_label.setOpenExternalLinks(True)
  3932. lic_lbl_header = QtWidgets.QLabel(
  3933. '%s:<br>%s<br>' % (
  3934. _('Licensed under the MIT license'),
  3935. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  3936. "http://www.opensource.org/licenses/mit-license.php</a>"
  3937. )
  3938. )
  3939. lic_lbl_header.setOpenExternalLinks(True)
  3940. lic_lbl_body = QtWidgets.QLabel(
  3941. _(
  3942. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3943. 'of this software and associated documentation files (the "Software"), to deal\n'
  3944. 'in the Software without restriction, including without limitation the rights\n'
  3945. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3946. 'copies of the Software, and to permit persons to whom the Software is\n'
  3947. 'furnished to do so, subject to the following conditions:\n\n'
  3948. 'The above copyright notice and this permission notice shall be included in\n'
  3949. 'all copies or substantial portions of the Software.\n\n'
  3950. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3951. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3952. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3953. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3954. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3955. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3956. 'THE SOFTWARE.'
  3957. )
  3958. )
  3959. attributions_label = QtWidgets.QLabel(
  3960. _(
  3961. 'Some of the icons used are from the following sources:<br>'
  3962. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  3963. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3964. 'title="Flaticon">www.flaticon.com</a></div>'
  3965. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  3966. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  3967. )
  3968. )
  3969. # layouts
  3970. layout1 = QtWidgets.QVBoxLayout()
  3971. layout1_1 = QtWidgets.QHBoxLayout()
  3972. layout1_2 = QtWidgets.QHBoxLayout()
  3973. layout2 = QtWidgets.QHBoxLayout()
  3974. layout3 = QtWidgets.QHBoxLayout()
  3975. self.setLayout(layout1)
  3976. layout1.addLayout(layout1_1)
  3977. layout1.addLayout(layout1_2)
  3978. layout1.addLayout(layout2)
  3979. layout1.addLayout(layout3)
  3980. layout1_1.addStretch()
  3981. layout1_1.addWidget(description_label)
  3982. layout1_2.addWidget(tab_widget)
  3983. self.splash_tab = QtWidgets.QWidget()
  3984. self.splash_tab.setObjectName("splash_about")
  3985. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3986. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3987. tab_widget.addTab(self.splash_tab, _("Splash"))
  3988. self.programmmers_tab = QtWidgets.QWidget()
  3989. self.programmmers_tab.setObjectName("programmers_about")
  3990. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3991. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3992. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3993. self.translators_tab = QtWidgets.QWidget()
  3994. self.translators_tab.setObjectName("translators_about")
  3995. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3996. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3997. tab_widget.addTab(self.translators_tab, _("Translators"))
  3998. self.license_tab = QtWidgets.QWidget()
  3999. self.license_tab.setObjectName("license_about")
  4000. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  4001. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  4002. tab_widget.addTab(self.license_tab, _("License"))
  4003. self.attributions_tab = QtWidgets.QWidget()
  4004. self.attributions_tab.setObjectName("attributions_about")
  4005. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  4006. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  4007. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  4008. self.splash_tab_layout.addWidget(logo, stretch=0)
  4009. self.splash_tab_layout.addWidget(title, stretch=1)
  4010. pal = QtGui.QPalette()
  4011. pal.setColor(QtGui.QPalette.Background, Qt.white)
  4012. self.prog_grid_lay = QtWidgets.QGridLayout()
  4013. self.prog_grid_lay.setHorizontalSpacing(20)
  4014. self.prog_grid_lay.setColumnStretch(0, 0)
  4015. self.prog_grid_lay.setColumnStretch(2, 1)
  4016. prog_widget = QtWidgets.QWidget()
  4017. prog_widget.setLayout(self.prog_grid_lay)
  4018. prog_scroll = QtWidgets.QScrollArea()
  4019. prog_scroll.setWidget(prog_widget)
  4020. prog_scroll.setWidgetResizable(True)
  4021. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  4022. prog_scroll.setPalette(pal)
  4023. self.programmmers_tab_layout.addWidget(prog_scroll)
  4024. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  4025. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  4026. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  4027. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  4028. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  4029. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  4030. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  4031. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  4032. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  4033. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  4034. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  4035. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  4036. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  4037. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  4038. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  4039. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  4040. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  4041. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 11, 0)
  4042. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  4043. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  4044. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 14, 0)
  4045. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 12, 0)
  4046. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 15, 0)
  4047. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 16, 0)
  4048. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 17, 0)
  4049. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 18, 0)
  4050. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  4051. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 20, 0)
  4052. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 21, 0)
  4053. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 22, 0)
  4054. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 23, 0)
  4055. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 24, 0)
  4056. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 25, 0)
  4057. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 26, 0)
  4058. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 27, 0)
  4059. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 28, 0)
  4060. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 29, 0)
  4061. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 30, 0)
  4062. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 31, 0)
  4063. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 34, 0)
  4064. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  4065. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  4066. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  4067. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  4068. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  4069. self.translator_grid_lay = QtWidgets.QGridLayout()
  4070. self.translator_grid_lay.setColumnStretch(0, 0)
  4071. self.translator_grid_lay.setColumnStretch(1, 0)
  4072. self.translator_grid_lay.setColumnStretch(2, 1)
  4073. self.translator_grid_lay.setColumnStretch(3, 0)
  4074. # trans_widget = QtWidgets.QWidget()
  4075. # trans_widget.setLayout(self.translator_grid_lay)
  4076. # self.translators_tab_layout.addWidget(trans_widget)
  4077. # self.translators_tab_layout.addStretch()
  4078. trans_widget = QtWidgets.QWidget()
  4079. trans_widget.setLayout(self.translator_grid_lay)
  4080. trans_scroll = QtWidgets.QScrollArea()
  4081. trans_scroll.setWidget(trans_widget)
  4082. trans_scroll.setWidgetResizable(True)
  4083. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  4084. trans_scroll.setPalette(pal)
  4085. self.translators_tab_layout.addWidget(trans_scroll)
  4086. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  4087. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  4088. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  4089. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  4090. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  4091. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  4092. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  4093. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  4094. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  4095. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  4096. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  4097. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  4098. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 3, 1)
  4099. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 3, 2)
  4100. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  4101. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  4102. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  4103. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  4104. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  4105. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  4106. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  4107. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  4108. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 6, 1)
  4109. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 6, 2)
  4110. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  4111. self.translator_grid_lay.setColumnStretch(0, 0)
  4112. self.translators_tab_layout.addStretch()
  4113. self.license_tab_layout.addWidget(lic_lbl_header)
  4114. self.license_tab_layout.addWidget(lic_lbl_body)
  4115. self.license_tab_layout.addStretch()
  4116. self.attributions_tab_layout.addWidget(attributions_label)
  4117. self.attributions_tab_layout.addStretch()
  4118. layout3.addStretch()
  4119. layout3.addWidget(closebtn)
  4120. closebtn.clicked.connect(self.accept)
  4121. AboutDialog(app=self, parent=self.ui).exec_()
  4122. def install_bookmarks(self, book_dict=None):
  4123. """
  4124. Install the bookmarks actions in the Help menu -> Bookmarks
  4125. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  4126. :return: None
  4127. """
  4128. if book_dict is None:
  4129. self.defaults["global_bookmarks"].update(
  4130. {
  4131. '1': ['FlatCAM', "http://flatcam.org"],
  4132. '2': ['Backup Site', ""]
  4133. }
  4134. )
  4135. else:
  4136. self.defaults["global_bookmarks"].clear()
  4137. self.defaults["global_bookmarks"].update(book_dict)
  4138. # first try to disconnect if somehow they get connected from elsewhere
  4139. for act in self.ui.menuhelp_bookmarks.actions():
  4140. try:
  4141. act.triggered.disconnect()
  4142. except TypeError:
  4143. pass
  4144. # clear all actions except the last one who is the Bookmark manager
  4145. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  4146. pass
  4147. else:
  4148. self.ui.menuhelp_bookmarks.removeAction(act)
  4149. bm_limit = int(self.defaults["global_bookmarks_limit"])
  4150. if self.defaults["global_bookmarks"]:
  4151. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  4152. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  4153. # the JSON is first making the keys as strings (therefore I have to use strings too
  4154. # or do the conversion :(
  4155. # )
  4156. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  4157. # the '10' entry jsut after '1' therefore ordering as strings
  4158. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  4159. key=lambda x: int(x[0]))
  4160. for entry, bookmark in sorted_bookmarks:
  4161. title = bookmark[0]
  4162. weblink = bookmark[1]
  4163. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  4164. act.setText(title)
  4165. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  4166. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  4167. if title == 'Backup Site' and weblink == "":
  4168. act.triggered.connect(self.on_backup_site)
  4169. else:
  4170. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  4171. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  4172. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  4173. def on_bookmarks_manager(self):
  4174. """
  4175. Adds the bookmark manager in a Tab in Plot Area
  4176. :return:
  4177. """
  4178. for idx in range(self.ui.plot_tab_area.count()):
  4179. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  4180. # there can be only one instance of Bookmark Manager at one time
  4181. return
  4182. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  4183. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  4184. # add the tab if it was closed
  4185. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  4186. # delete the absolute and relative position and messages in the infobar
  4187. self.ui.position_label.setText("")
  4188. self.ui.rel_position_label.setText("")
  4189. # Switch plot_area to preferences page
  4190. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  4191. def on_backup_site(self):
  4192. msgbox = QtWidgets.QMessageBox()
  4193. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  4194. "1. FlatCAM.org website is down\n"
  4195. "2. Someone forked FlatCAM project and wants to point\n"
  4196. "to his own website\n\n"
  4197. "If you can't get any informations about FlatCAM beta\n"
  4198. "use the YouTube channel link from the Help menu."))
  4199. msgbox.setWindowTitle(_("Alternative website"))
  4200. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  4201. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  4202. msgbox.setDefaultButton(bt_yes)
  4203. msgbox.exec_()
  4204. # response = msgbox.clickedButton()
  4205. def on_file_savedefaults(self):
  4206. """
  4207. Callback for menu item File->Save Defaults. Saves application default options
  4208. ``self.defaults`` to current_defaults.FlatConfig.
  4209. :return: None
  4210. """
  4211. self.save_defaults()
  4212. # def on_app_exit(self):
  4213. # self.report_usage("on_app_exit()")
  4214. #
  4215. # if self.collection.get_list():
  4216. # msgbox = QtWidgets.QMessageBox()
  4217. # # msgbox.setText("<B>Save changes ...</B>")
  4218. # msgbox.setText("There are files/objects opened in FlatCAM. "
  4219. # "\n"
  4220. # "Do you want to Save the project?")
  4221. # msgbox.setWindowTitle("Save changes")
  4222. # msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4223. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  4224. # QtWidgets.QMessageBox.Cancel)
  4225. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  4226. #
  4227. # response = msgbox.exec_()
  4228. #
  4229. # if response == QtWidgets.QMessageBox.Yes:
  4230. # self.on_file_saveprojectas(thread=False)
  4231. # elif response == QtWidgets.QMessageBox.Cancel:
  4232. # return
  4233. # self.save_defaults()
  4234. # else:
  4235. # self.save_defaults()
  4236. # log.debug("Application defaults saved ... Exit event.")
  4237. # QtWidgets.qApp.quit()
  4238. def save_defaults(self, silent=False, data_path=None, first_time=False):
  4239. """
  4240. Saves application default options
  4241. ``self.defaults`` to current_defaults.FlatConfig file.
  4242. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  4243. used at the next launch of the application.
  4244. :param silent: whether to display a message in status bar or not; boolean
  4245. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  4246. When the application is portable it should be a mobile location.
  4247. :return: None
  4248. """
  4249. self.report_usage("save_defaults")
  4250. if data_path is None:
  4251. data_path = self.data_path
  4252. # Read options from file
  4253. try:
  4254. f = open(data_path + "/current_defaults.FlatConfig")
  4255. defaults_file_content = f.read()
  4256. f.close()
  4257. except Exception:
  4258. e = sys.exc_info()[0]
  4259. App.log.error("Could not load defaults file.")
  4260. App.log.error(str(e))
  4261. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load defaults file."))
  4262. return
  4263. try:
  4264. defaults = json.loads(defaults_file_content)
  4265. except Exception:
  4266. e = sys.exc_info()[0]
  4267. App.log.error("Failed to parse defaults file.")
  4268. App.log.error(str(e))
  4269. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse defaults file."))
  4270. return
  4271. # Update options
  4272. self.defaults_read_form()
  4273. defaults.update(self.defaults)
  4274. self.propagate_defaults(silent=True)
  4275. # Save the toolbar view
  4276. tb_status = 0
  4277. if self.ui.toolbarfile.isVisible():
  4278. tb_status += 1
  4279. if self.ui.toolbargeo.isVisible():
  4280. tb_status += 2
  4281. if self.ui.toolbarview.isVisible():
  4282. tb_status += 4
  4283. if self.ui.toolbartools.isVisible():
  4284. tb_status += 8
  4285. if self.ui.exc_edit_toolbar.isVisible():
  4286. tb_status += 16
  4287. if self.ui.geo_edit_toolbar.isVisible():
  4288. tb_status += 32
  4289. if self.ui.grb_edit_toolbar.isVisible():
  4290. tb_status += 64
  4291. if self.ui.snap_toolbar.isVisible():
  4292. tb_status += 128
  4293. if self.ui.toolbarshell.isVisible():
  4294. tb_status += 256
  4295. if first_time is False:
  4296. self.defaults["global_toolbar_view"] = tb_status
  4297. # Save update options
  4298. filename = data_path + "/current_defaults.FlatConfig"
  4299. try:
  4300. f = open(filename, "w")
  4301. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  4302. f.close()
  4303. except Exception as e:
  4304. log.debug("App.save_defaults() --> %s" % str(e))
  4305. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  4306. return
  4307. if not silent:
  4308. self.inform.emit('[success] %s' % _("Preferences saved."))
  4309. def save_factory_defaults(self, silent_message=False, data_path=None):
  4310. """
  4311. Saves application factory default options
  4312. ``self.defaults`` to factory_defaults.FlatConfig.
  4313. It's a one time job done just after the first install.
  4314. :param silent_message: whether to display a message in status bar or not; boolean
  4315. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  4316. When the application is portable it should be a mobile location.
  4317. :return: None
  4318. """
  4319. self.report_usage("save_factory_defaults")
  4320. if data_path is None:
  4321. data_path = self.data_path
  4322. # Read options from file
  4323. try:
  4324. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  4325. factory_defaults_file_content = f_f_def.read()
  4326. f_f_def.close()
  4327. except Exception:
  4328. e = sys.exc_info()[0]
  4329. App.log.error("Could not load factory defaults file.")
  4330. App.log.error(str(e))
  4331. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load factory defaults file."))
  4332. return
  4333. try:
  4334. factory_defaults = json.loads(factory_defaults_file_content)
  4335. except Exception:
  4336. e = sys.exc_info()[0]
  4337. App.log.error("Failed to parse factory defaults file.")
  4338. App.log.error(str(e))
  4339. if silent_message is False:
  4340. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse factory defaults file."))
  4341. return
  4342. # Update options
  4343. self.defaults_read_form()
  4344. factory_defaults.update(self.defaults)
  4345. self.propagate_defaults(silent=True)
  4346. # Save update options
  4347. try:
  4348. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  4349. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  4350. f_f_def_s.close()
  4351. except Exception as e:
  4352. log.debug("App.save_factory_default() save update --> %s" % str(e))
  4353. if silent_message is False:
  4354. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write factory defaults to file."))
  4355. return
  4356. if silent_message is False:
  4357. self.inform.emit(_("Factory defaults saved."))
  4358. def final_save(self):
  4359. """
  4360. Callback for doing a preferences save to file whenever the application is about to quit.
  4361. If the project has changes, it will ask the user to save the project.
  4362. :return: None
  4363. """
  4364. if self.save_in_progress:
  4365. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  4366. return
  4367. if self.should_we_save and self.collection.get_list():
  4368. msgbox = QtWidgets.QMessageBox()
  4369. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  4370. "\n"
  4371. "Do you want to Save the project?"))
  4372. msgbox.setWindowTitle(_("Save changes"))
  4373. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4374. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4375. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4376. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4377. msgbox.setDefaultButton(bt_yes)
  4378. msgbox.exec_()
  4379. response = msgbox.clickedButton()
  4380. if response == bt_yes:
  4381. try:
  4382. self.trayIcon.hide()
  4383. except Exception:
  4384. pass
  4385. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  4386. elif response == bt_no:
  4387. try:
  4388. self.trayIcon.hide()
  4389. except Exception:
  4390. pass
  4391. self.quit_application()
  4392. elif response == bt_cancel:
  4393. return
  4394. else:
  4395. try:
  4396. self.trayIcon.hide()
  4397. except Exception:
  4398. pass
  4399. self.quit_application()
  4400. def quit_application(self):
  4401. """
  4402. Called (as a pyslot or not) when the application is quit.
  4403. :return: None
  4404. """
  4405. self.save_defaults(silent=True)
  4406. log.debug("App.final_save() --> App Defaults saved.")
  4407. if self.cmd_line_headless != 1:
  4408. # save app state to file
  4409. stgs = QSettings("Open Source", "FlatCAM")
  4410. stgs.setValue('saved_gui_state', self.ui.saveState())
  4411. stgs.setValue('maximized_gui', self.ui.isMaximized())
  4412. stgs.setValue(
  4413. 'language',
  4414. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  4415. )
  4416. stgs.setValue(
  4417. 'notebook_font_size',
  4418. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  4419. )
  4420. stgs.setValue(
  4421. 'axis_font_size',
  4422. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  4423. )
  4424. stgs.setValue(
  4425. 'textbox_font_size',
  4426. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  4427. )
  4428. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  4429. stgs.setValue(
  4430. 'machinist',
  4431. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  4432. )
  4433. # This will write the setting to the platform specific storage.
  4434. del stgs
  4435. log.debug("App.final_save() --> App UI state saved.")
  4436. # try to quit the QThread that run ArgsThread class
  4437. try:
  4438. self.th.quit()
  4439. except Exception:
  4440. pass
  4441. # try to quit the Socket opened by ArgsThread class
  4442. try:
  4443. self.new_launch.listener.close()
  4444. except Exception:
  4445. pass
  4446. # quit app by signalling for self.kill_app() method
  4447. self.close_app_signal.emit()
  4448. def kill_app(self):
  4449. QtWidgets.qApp.quit()
  4450. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  4451. # we use the following command
  4452. sys.exit(0)
  4453. def on_portable_checked(self, state):
  4454. """
  4455. Callback called when the checkbox in Preferences GUI is checked.
  4456. It will set the application as portable by creating the preferences and recent files in the
  4457. 'config' folder found in the FlatCAM installation folder.
  4458. :param state: boolean, the state of the checkbox when clicked/checked
  4459. :return:
  4460. """
  4461. line_no = 0
  4462. data = None
  4463. if sys.platform != 'win32':
  4464. # this won't work in Linux or MacOS
  4465. return
  4466. # test if the app was frozen and choose the path for the configuration file
  4467. if getattr(sys, "frozen", False) is True:
  4468. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  4469. else:
  4470. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  4471. config_file = current_data_path + '\\configuration.txt'
  4472. try:
  4473. with open(config_file, 'r') as f:
  4474. try:
  4475. data = f.readlines()
  4476. except Exception as e:
  4477. log.debug('App.__init__() -->%s' % str(e))
  4478. return
  4479. except FileNotFoundError:
  4480. pass
  4481. for line in data:
  4482. line = line.strip('\n')
  4483. param = str(line).rpartition('=')
  4484. if param[0] == 'portable':
  4485. break
  4486. line_no += 1
  4487. if state:
  4488. data[line_no] = 'portable=True\n'
  4489. # create the new defauults files
  4490. # create current_defaults.FlatConfig file if there is none
  4491. try:
  4492. f = open(current_data_path + '/current_defaults.FlatConfig')
  4493. f.close()
  4494. except IOError:
  4495. App.log.debug('Creating empty current_defaults.FlatConfig')
  4496. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4497. json.dump({}, f)
  4498. f.close()
  4499. # create factory_defaults.FlatConfig file if there is none
  4500. try:
  4501. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4502. f.close()
  4503. except IOError:
  4504. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4505. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4506. json.dump({}, f)
  4507. f.close()
  4508. try:
  4509. f = open(current_data_path + '/recent.json')
  4510. f.close()
  4511. except IOError:
  4512. App.log.debug('Creating empty recent.json')
  4513. f = open(current_data_path + '/recent.json', 'w')
  4514. json.dump([], f)
  4515. f.close()
  4516. try:
  4517. fp = open(current_data_path + '/recent_projects.json')
  4518. fp.close()
  4519. except IOError:
  4520. App.log.debug('Creating empty recent_projects.json')
  4521. fp = open(current_data_path + '/recent_projects.json', 'w')
  4522. json.dump([], fp)
  4523. fp.close()
  4524. # save the current defaults to the new defaults file
  4525. self.save_defaults(silent=True, data_path=current_data_path)
  4526. self.save_factory_defaults(silent_message=True, data_path=current_data_path)
  4527. else:
  4528. data[line_no] = 'portable=False\n'
  4529. with open(config_file, 'w') as f:
  4530. f.writelines(data)
  4531. def on_toggle_shell(self):
  4532. """
  4533. Toggle shell: if is visible close it, if it is closed then open it
  4534. :return: None
  4535. """
  4536. self.report_usage("on_toggle_shell()")
  4537. if self.ui.shell_dock.isVisible():
  4538. self.ui.shell_dock.hide()
  4539. else:
  4540. self.ui.shell_dock.show()
  4541. def on_register_files(self, obj_type=None):
  4542. """
  4543. Called whenever there is a need to register file extensions with FlatCAM.
  4544. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4545. :param obj_type: the type of object to be register for.
  4546. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4547. :return: None
  4548. """
  4549. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4550. new_reg_path = 'Software\\Classes\\'
  4551. # find if the current user is admin
  4552. try:
  4553. is_admin = os.getuid() == 0
  4554. except AttributeError:
  4555. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4556. if is_admin is True:
  4557. root_path = winreg.HKEY_LOCAL_MACHINE
  4558. else:
  4559. root_path = winreg.HKEY_CURRENT_USER
  4560. # create the keys
  4561. def set_reg(name, root_path, new_reg_path, value):
  4562. try:
  4563. winreg.CreateKey(root_path, new_reg_path)
  4564. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4565. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4566. return True
  4567. except WindowsError:
  4568. return False
  4569. # delete key in registry
  4570. def delete_reg(root_path, reg_path, key_to_del):
  4571. key_to_del_path = reg_path + key_to_del
  4572. try:
  4573. winreg.DeleteKey(root_path, key_to_del_path)
  4574. return True
  4575. except WindowsError:
  4576. return False
  4577. if obj_type is None or obj_type == 'excellon':
  4578. exc_list = \
  4579. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4580. exc_list = [x for x in exc_list if x != '']
  4581. # register all keys in the Preferences window
  4582. for ext in exc_list:
  4583. new_k = new_reg_path + '.%s' % ext
  4584. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4585. # and unregister those that are no longer in the Preferences windows but are in the file
  4586. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4587. if ext not in exc_list:
  4588. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4589. # now write the updated extensions to the self.defaults
  4590. # new_ext = ''
  4591. # for ext in exc_list:
  4592. # new_ext = new_ext + ext + ', '
  4593. # self.defaults["fa_excellon"] = new_ext
  4594. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4595. if obj_type is None or obj_type == 'gcode':
  4596. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4597. gco_list = [x for x in gco_list if x != '']
  4598. # register all keys in the Preferences window
  4599. for ext in gco_list:
  4600. new_k = new_reg_path + '.%s' % ext
  4601. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4602. # and unregister those that are no longer in the Preferences windows but are in the file
  4603. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4604. if ext not in gco_list:
  4605. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4606. # now write the updated extensions to the self.defaults
  4607. # new_ext = ''
  4608. # for ext in gco_list:
  4609. # new_ext = new_ext + ext + ', '
  4610. # self.defaults["fa_gcode"] = new_ext
  4611. self.inform.emit('[success] %s' %
  4612. _("Selected GCode file extensions registered with FlatCAM."))
  4613. if obj_type is None or obj_type == 'gerber':
  4614. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4615. grb_list = [x for x in grb_list if x != '']
  4616. # register all keys in the Preferences window
  4617. for ext in grb_list:
  4618. new_k = new_reg_path + '.%s' % ext
  4619. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4620. # and unregister those that are no longer in the Preferences windows but are in the file
  4621. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4622. if ext not in grb_list:
  4623. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4624. # now write the updated extensions to the self.defaults
  4625. # new_ext = ''
  4626. # for ext in grb_list:
  4627. # new_ext = new_ext + ext + ', '
  4628. # self.defaults["fa_gerber"] = new_ext
  4629. self.inform.emit('[success] %s' %
  4630. _("Selected Gerber file extensions registered with FlatCAM."))
  4631. def add_extension(self, ext_type):
  4632. """
  4633. Add a file extension to the list for a specific object
  4634. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4635. :return:
  4636. """
  4637. if ext_type == 'excellon':
  4638. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4639. if new_ext == '':
  4640. return
  4641. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4642. if new_ext in old_val:
  4643. return
  4644. old_val.append(new_ext)
  4645. old_val.sort()
  4646. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4647. if ext_type == 'gcode':
  4648. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4649. if new_ext == '':
  4650. return
  4651. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4652. if new_ext in old_val:
  4653. return
  4654. old_val.append(new_ext)
  4655. old_val.sort()
  4656. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4657. if ext_type == 'gerber':
  4658. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4659. if new_ext == '':
  4660. return
  4661. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4662. if new_ext in old_val:
  4663. return
  4664. old_val.append(new_ext)
  4665. old_val.sort()
  4666. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4667. if ext_type == 'keyword':
  4668. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4669. if new_kw == '':
  4670. return
  4671. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4672. if new_kw in old_val:
  4673. return
  4674. old_val.append(new_kw)
  4675. old_val.sort()
  4676. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4677. # update the self.myKeywords so the model is updated
  4678. self.autocomplete_kw_list = \
  4679. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4680. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4681. self.shell._edit.set_model_data(self.myKeywords)
  4682. def del_extension(self, ext_type):
  4683. """
  4684. Remove a file extension from the list for a specific object
  4685. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4686. :return:
  4687. """
  4688. if ext_type == 'excellon':
  4689. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4690. if new_ext == '':
  4691. return
  4692. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4693. if new_ext not in old_val:
  4694. return
  4695. old_val.remove(new_ext)
  4696. old_val.sort()
  4697. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4698. if ext_type == 'gcode':
  4699. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4700. if new_ext == '':
  4701. return
  4702. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4703. if new_ext not in old_val:
  4704. return
  4705. old_val.remove(new_ext)
  4706. old_val.sort()
  4707. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4708. if ext_type == 'gerber':
  4709. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4710. if new_ext == '':
  4711. return
  4712. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4713. if new_ext not in old_val:
  4714. return
  4715. old_val.remove(new_ext)
  4716. old_val.sort()
  4717. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4718. if ext_type == 'keyword':
  4719. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4720. if new_kw == '':
  4721. return
  4722. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4723. if new_kw not in old_val:
  4724. return
  4725. old_val.remove(new_kw)
  4726. old_val.sort()
  4727. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4728. # update the self.myKeywords so the model is updated
  4729. self.autocomplete_kw_list = \
  4730. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4731. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4732. self.shell._edit.set_model_data(self.myKeywords)
  4733. def restore_extensions(self, ext_type):
  4734. """
  4735. Restore all file extensions associations with FlatCAM, for a specific object
  4736. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4737. :return:
  4738. """
  4739. if ext_type == 'excellon':
  4740. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4741. # for the ability to open Excellon files with .txt extension
  4742. new_exc_list = deepcopy(self.exc_list)
  4743. try:
  4744. new_exc_list.remove('txt')
  4745. except ValueError:
  4746. pass
  4747. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4748. if ext_type == 'gcode':
  4749. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4750. if ext_type == 'gerber':
  4751. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4752. if ext_type == 'keyword':
  4753. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4754. # update the self.myKeywords so the model is updated
  4755. self.autocomplete_kw_list = self.default_keywords
  4756. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4757. self.shell._edit.set_model_data(self.myKeywords)
  4758. def delete_all_extensions(self, ext_type):
  4759. """
  4760. Delete all file extensions associations with FlatCAM, for a specific object
  4761. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4762. :return:
  4763. """
  4764. if ext_type == 'excellon':
  4765. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4766. if ext_type == 'gcode':
  4767. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4768. if ext_type == 'gerber':
  4769. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4770. if ext_type == 'keyword':
  4771. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4772. # update the self.myKeywords so the model is updated
  4773. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4774. self.shell._edit.set_model_data(self.myKeywords)
  4775. def on_edit_join(self, name=None):
  4776. """
  4777. Callback for Edit->Join. Joins the selected geometry objects into
  4778. a new one.
  4779. :return: None
  4780. """
  4781. self.report_usage("on_edit_join()")
  4782. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4783. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4784. geo_type_set = set()
  4785. objs = self.collection.get_selected()
  4786. if len(objs) < 2:
  4787. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4788. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4789. return 'fail'
  4790. for obj in objs:
  4791. geo_type_set.add(obj.multigeo)
  4792. # if len(geo_type_list) == 1 means that all list elements are the same
  4793. if len(geo_type_set) != 1:
  4794. self.inform.emit('[ERROR] %s' %
  4795. _("Failed join. The Geometry objects are of different types.\n"
  4796. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4797. "convert from one to another and retry joining \n"
  4798. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4799. "the result may not be what was expected. \n"
  4800. "Check the generated GCODE."))
  4801. return
  4802. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4803. if True in geo_type_set:
  4804. def initialize(geo_obj, app):
  4805. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  4806. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  4807. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4808. for v in geo_obj.tools.values():
  4809. v['data']['name'] = obj_name_multi
  4810. self.new_object("geometry", obj_name_multi, initialize)
  4811. else:
  4812. def initialize(geo_obj, app):
  4813. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  4814. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  4815. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4816. for v in geo_obj.tools.values():
  4817. v['data']['name'] = obj_name_single
  4818. self.new_object("geometry", obj_name_single, initialize)
  4819. self.should_we_save = True
  4820. def on_edit_join_exc(self):
  4821. """
  4822. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4823. a new Excellon.
  4824. :return: None
  4825. """
  4826. self.report_usage("on_edit_join_exc()")
  4827. objs = self.collection.get_selected()
  4828. for obj in objs:
  4829. if not isinstance(obj, FlatCAMExcellon):
  4830. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  4831. return
  4832. if len(objs) < 2:
  4833. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4834. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4835. return 'fail'
  4836. def initialize(exc_obj, app):
  4837. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=exc_obj)
  4838. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  4839. self.new_object("excellon", 'Combo_Excellon', initialize)
  4840. self.should_we_save = True
  4841. def on_edit_join_grb(self):
  4842. """
  4843. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4844. a new Gerber object.
  4845. :return: None
  4846. """
  4847. self.report_usage("on_edit_join_grb()")
  4848. objs = self.collection.get_selected()
  4849. for obj in objs:
  4850. if not isinstance(obj, FlatCAMGerber):
  4851. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  4852. return
  4853. if len(objs) < 2:
  4854. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4855. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4856. return 'fail'
  4857. def initialize(grb_obj, app):
  4858. FlatCAMGerber.merge(self, grb_list=objs, grb_final=grb_obj)
  4859. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  4860. self.new_object("gerber", 'Combo_Gerber', initialize)
  4861. self.should_we_save = True
  4862. def on_convert_singlegeo_to_multigeo(self):
  4863. """
  4864. Called for converting a Geometry object from single-geo to multi-geo.
  4865. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4866. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4867. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4868. the solid-geometry of that tool.
  4869. :return: None
  4870. """
  4871. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4872. obj = self.collection.get_active()
  4873. if obj is None:
  4874. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  4875. return
  4876. if not isinstance(obj, FlatCAMGeometry):
  4877. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4878. return
  4879. obj.multigeo = True
  4880. for tooluid, dict_value in obj.tools.items():
  4881. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4882. if not isinstance(obj.solid_geometry, list):
  4883. obj.solid_geometry = [obj.solid_geometry]
  4884. obj.solid_geometry[:] = []
  4885. obj.plot()
  4886. self.should_we_save = True
  4887. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  4888. def on_convert_multigeo_to_singlegeo(self):
  4889. """
  4890. Called for converting a Geometry object from multi-geo to single-geo.
  4891. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4892. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4893. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4894. the solid-geometry of that tool.
  4895. :return: None
  4896. """
  4897. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4898. obj = self.collection.get_active()
  4899. if obj is None:
  4900. self.inform.emit('[ERROR_NOTCL] %s' %
  4901. _("Failed. Select a Geometry Object and try again."))
  4902. return
  4903. if not isinstance(obj, FlatCAMGeometry):
  4904. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4905. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4906. return
  4907. obj.multigeo = False
  4908. total_solid_geometry = []
  4909. for tooluid, dict_value in obj.tools.items():
  4910. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4911. # clear the original geometry
  4912. dict_value['solid_geometry'][:] = []
  4913. obj.solid_geometry = deepcopy(total_solid_geometry)
  4914. obj.plot()
  4915. self.should_we_save = True
  4916. self.inform.emit('[success] %s' %
  4917. _("A Geometry object was converted to SingleGeo type."))
  4918. def on_defaults_dict_change(self, field):
  4919. """
  4920. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4921. Edit -> Preferences tab window.
  4922. :param field: the key of the self.defaults dictionary that was changed.
  4923. :return: None
  4924. """
  4925. self.defaults_write_form_field(field)
  4926. if field == "units":
  4927. self.set_screen_units(self.defaults['units'])
  4928. def set_screen_units(self, units):
  4929. """
  4930. Set the FlatCAM units on the status bar.
  4931. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4932. :return: None
  4933. """
  4934. self.ui.units_label.setText("[" + units.lower() + "]")
  4935. def on_toggle_units_click(self):
  4936. try:
  4937. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4938. except (TypeError, AttributeError):
  4939. pass
  4940. if self.defaults["units"] == 'MM':
  4941. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4942. else:
  4943. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4944. self.on_toggle_units(no_pref=True)
  4945. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4946. lambda: self.on_toggle_units(no_pref=False))
  4947. def on_toggle_units(self, no_pref=False):
  4948. """
  4949. Callback for the Units radio-button change in the Preferences tab.
  4950. Changes the application's default units adn for the project too.
  4951. If changing the project's units, the change propagates to all of
  4952. the objects in the project.
  4953. :return: None
  4954. """
  4955. self.report_usage("on_toggle_units")
  4956. if self.toggle_units_ignore:
  4957. return
  4958. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4959. # If option is the same, then ignore
  4960. if new_units == self.defaults["units"].upper():
  4961. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4962. return
  4963. # Options to scale
  4964. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4965. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  4966. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4967. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4968. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4969. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4970. "excellon_editor_slot_lin_pitch",
  4971. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4972. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4973. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4974. "geometry_feedrate_probe", "geometry_startz",
  4975. 'cncjob_tooldia',
  4976. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4977. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  4978. "tools_nccnewdia",
  4979. "tools_2sided_drilldia", "tools_film_boundary",
  4980. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4981. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4982. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4983. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4984. "tools_transform_offset_y",
  4985. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4986. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4987. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4988. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4989. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  4990. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  4991. "tools_cr_h2h_val", "tools_cr_dh_val", "tools_fiducials_dia", "tools_fiducials_margin",
  4992. "tools_fiducials_line_thickness",
  4993. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  4994. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  4995. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  4996. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  4997. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  4998. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  4999. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  5000. def scale_defaults(sfactor):
  5001. for dim in dimensions:
  5002. if dim == 'excellon_toolchangexy':
  5003. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  5004. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  5005. coords_xy[0] *= sfactor
  5006. coords_xy[1] *= sfactor
  5007. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  5008. self.decimals, coords_xy[1])
  5009. elif dim == 'geometry_toolchangexy':
  5010. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  5011. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  5012. coords_xy[0] *= sfactor
  5013. coords_xy[1] *= sfactor
  5014. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  5015. self.decimals, coords_xy[1])
  5016. elif dim == 'geometry_cnctooldia':
  5017. if type(self.defaults["geometry_cnctooldia"]) == float:
  5018. tools_diameters = [self.defaults["geometry_cnctooldia"]]
  5019. else:
  5020. try:
  5021. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  5022. tools_diameters = [eval(a) for a in tools_string if a != '']
  5023. except Exception as e:
  5024. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  5025. continue
  5026. self.defaults['geometry_cnctooldia'] = ''
  5027. for t in range(len(tools_diameters)):
  5028. tools_diameters[t] *= sfactor
  5029. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  5030. elif dim == 'tools_ncctools':
  5031. if type(self.defaults["tools_ncctools"]) == float:
  5032. ncctools = [self.defaults["tools_ncctools"]]
  5033. else:
  5034. try:
  5035. tools_string = self.defaults["tools_ncctools"].split(",")
  5036. ncctools = [eval(a) for a in tools_string if a != '']
  5037. except Exception as e:
  5038. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  5039. continue
  5040. self.defaults['tools_ncctools'] = ''
  5041. for t in range(len(ncctools)):
  5042. ncctools[t] *= sfactor
  5043. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  5044. elif dim == 'tools_solderpaste_tools':
  5045. if type(self.defaults["tools_solderpaste_tools"]) == float:
  5046. sptools = [self.defaults["tools_solderpaste_tools"]]
  5047. else:
  5048. try:
  5049. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  5050. sptools = [eval(a) for a in tools_string if a != '']
  5051. except Exception as e:
  5052. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  5053. continue
  5054. self.defaults['tools_solderpaste_tools'] = ""
  5055. for t in range(len(sptools)):
  5056. sptools[t] *= sfactor
  5057. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  5058. elif dim == 'tools_solderpaste_xy_toolchange':
  5059. try:
  5060. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  5061. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  5062. sp_coords[0] *= sfactor
  5063. sp_coords[1] *= sfactor
  5064. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  5065. self.decimals, sp_coords[1])
  5066. except Exception as e:
  5067. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  5068. continue
  5069. elif dim == 'global_gridx' or dim == 'global_gridy':
  5070. if new_units == 'IN':
  5071. try:
  5072. val = float(self.defaults[dim]) * sfactor
  5073. except Exception as e:
  5074. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  5075. continue
  5076. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  5077. else:
  5078. try:
  5079. val = float(self.defaults[dim]) * sfactor
  5080. except Exception as e:
  5081. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  5082. continue
  5083. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  5084. else:
  5085. if self.defaults[dim]:
  5086. try:
  5087. val = float(self.defaults[dim]) * sfactor
  5088. except Exception as e:
  5089. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  5090. continue
  5091. self.defaults[dim] = val
  5092. # The scaling factor depending on choice of units.
  5093. factor = 25.4 if new_units == 'MM' else 1/25.4
  5094. # Changing project units. Warn user.
  5095. msgbox = QtWidgets.QMessageBox()
  5096. msgbox.setWindowTitle(_("Toggle Units"))
  5097. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  5098. msgbox.setText(_("Changing the units of the project\n"
  5099. "will scale all objects.\n\n"
  5100. "Do you want to continue?"))
  5101. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5102. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5103. msgbox.setDefaultButton(bt_ok)
  5104. msgbox.exec_()
  5105. response = msgbox.clickedButton()
  5106. if response == bt_ok:
  5107. if no_pref is False:
  5108. self.defaults_read_form()
  5109. scale_defaults(factor)
  5110. self.defaults_write_form(fl_units=new_units)
  5111. self.defaults["units"] = new_units
  5112. # update the defaults from form, some may assume that the conversion is enough and it's not
  5113. self.on_options_app2project()
  5114. # update the objects
  5115. for obj in self.collection.get_list():
  5116. obj.convert_units(new_units)
  5117. # make that the properties stored in the object are also updated
  5118. self.object_changed.emit(obj)
  5119. # rebuild the object UI
  5120. obj.build_ui()
  5121. # change this only if the workspace is active
  5122. if self.defaults['global_workspace'] is True:
  5123. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  5124. # adjust the grid values on the main toolbar
  5125. val_x = float(self.defaults['global_gridx']) * factor
  5126. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  5127. current = self.collection.get_active()
  5128. if current is not None:
  5129. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  5130. if not isinstance(current, FlatCAMGeometry):
  5131. current.to_form()
  5132. # replot all objects
  5133. self.plot_all()
  5134. # set the status labels to reflect the current FlatCAM units
  5135. self.set_screen_units(new_units)
  5136. # signal to the app that we changed the object properties and it shoud save the project
  5137. self.should_we_save = True
  5138. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  5139. else:
  5140. # Undo toggling
  5141. self.toggle_units_ignore = True
  5142. if self.defaults['units'].upper() == 'MM':
  5143. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  5144. else:
  5145. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  5146. self.toggle_units_ignore = False
  5147. # store the grid values so they are not changed in the next step
  5148. val_x = float(self.defaults['global_gridx'])
  5149. val_y = float(self.defaults['global_gridy'])
  5150. self.inform.emit('[WARNING_NOTCL]%s' % _("Units conversion cancelled."))
  5151. self.defaults_read_form()
  5152. # the self.defaults_read_form() will update all defaults values in self.defaults from the GUI elements but
  5153. # I don't want it for the grid values, so I update them here
  5154. self.defaults['global_gridx'] = val_x
  5155. self.defaults['global_gridy'] = val_y
  5156. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  5157. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  5158. def on_fullscreen(self, disable=False):
  5159. self.report_usage("on_fullscreen()")
  5160. if self.toggle_fscreen is False and disable is False:
  5161. # self.ui.showFullScreen()
  5162. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  5163. a = self.ui.geometry()
  5164. self.x_pos = a.x()
  5165. self.y_pos = a.y()
  5166. self.width = a.width()
  5167. self.height = a.height()
  5168. # set new geometry to full desktop rect
  5169. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  5170. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  5171. # everything else will not work without this hack. This happen in Windows.
  5172. # https://bugreports.qt.io/browse/QTBUG-41309
  5173. desktop = QtWidgets.QApplication.desktop()
  5174. screen = desktop.screenNumber(QtGui.QCursor.pos())
  5175. rec = desktop.screenGeometry(screen)
  5176. x = rec.x() - 1
  5177. y = rec.y() - 1
  5178. h = rec.height() + 2
  5179. w = rec.width() + 2
  5180. self.ui.setGeometry(x, y, w, h)
  5181. self.ui.show()
  5182. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  5183. tb.setVisible(False)
  5184. self.ui.splitter_left.setVisible(False)
  5185. self.toggle_fscreen = True
  5186. elif self.toggle_fscreen is True or disable is True:
  5187. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  5188. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  5189. self.ui.showNormal()
  5190. self.restore_toolbar_view()
  5191. self.ui.splitter_left.setVisible(True)
  5192. self.toggle_fscreen = False
  5193. def on_toggle_plotarea(self):
  5194. self.report_usage("on_toggle_plotarea()")
  5195. try:
  5196. name = self.ui.plot_tab_area.widget(0).objectName()
  5197. except AttributeError:
  5198. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  5199. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  5200. self.ui.plot_tab_area.protectTab(0)
  5201. return
  5202. if name != 'plotarea':
  5203. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5204. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  5205. self.ui.plot_tab_area.protectTab(0)
  5206. else:
  5207. self.ui.plot_tab_area.closeTab(0)
  5208. def on_toggle_notebook(self):
  5209. if self.ui.splitter.sizes()[0] == 0:
  5210. self.ui.splitter.setSizes([1, 1])
  5211. self.ui.menu_toggle_nb.setChecked(True)
  5212. else:
  5213. self.ui.splitter.setSizes([0, 1])
  5214. self.ui.menu_toggle_nb.setChecked(False)
  5215. def on_toggle_axis(self):
  5216. self.report_usage("on_toggle_axis()")
  5217. if self.toggle_axis is False:
  5218. if self.is_legacy is False:
  5219. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  5220. parent=self.plotcanvas.view.scene)
  5221. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  5222. parent=self.plotcanvas.view.scene)
  5223. else:
  5224. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  5225. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  5226. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  5227. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  5228. self.plotcanvas.canvas.draw()
  5229. self.toggle_axis = True
  5230. else:
  5231. if self.is_legacy is False:
  5232. self.plotcanvas.v_line.parent = None
  5233. self.plotcanvas.h_line.parent = None
  5234. else:
  5235. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  5236. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  5237. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  5238. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  5239. self.plotcanvas.canvas.draw()
  5240. self.toggle_axis = False
  5241. def on_toggle_grid(self):
  5242. self.report_usage("on_toggle_grid()")
  5243. self.ui.grid_snap_btn.trigger()
  5244. self.on_grid_snap_triggered(state=True)
  5245. def on_toggle_grid_lines(self):
  5246. self.report_usage("on_toggle_grd_lines()")
  5247. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  5248. if tt_settings.contains("theme"):
  5249. theme = tt_settings.value('theme', type=str)
  5250. else:
  5251. theme = 'white'
  5252. if self.toggle_grid_lines is False:
  5253. if self.is_legacy is False:
  5254. if theme == 'white':
  5255. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  5256. else:
  5257. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  5258. else:
  5259. self.plotcanvas.axes.grid(True)
  5260. try:
  5261. self.plotcanvas.canvas.draw()
  5262. except IndexError:
  5263. pass
  5264. pass
  5265. self.toggle_grid_lines = True
  5266. else:
  5267. if self.is_legacy is False:
  5268. if theme == 'white':
  5269. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  5270. else:
  5271. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  5272. else:
  5273. self.plotcanvas.axes.grid(False)
  5274. try:
  5275. self.plotcanvas.canvas.draw()
  5276. except IndexError:
  5277. pass
  5278. self.toggle_grid_lines = False
  5279. if self.is_legacy is False:
  5280. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  5281. # - perhaps is a bug in VisPy implementation
  5282. if self.grid_status() is True:
  5283. self.app_cursor.enabled = False
  5284. self.app_cursor.enabled = True
  5285. else:
  5286. self.app_cursor.enabled = True
  5287. self.app_cursor.enabled = False
  5288. def show_preferences_gui(self):
  5289. """
  5290. Called to initialize and show the Preferences GUI
  5291. :return: None
  5292. """
  5293. self.gen_form = self.ui.general_defaults_form
  5294. self.ger_form = self.ui.gerber_defaults_form
  5295. self.exc_form = self.ui.excellon_defaults_form
  5296. self.geo_form = self.ui.geometry_defaults_form
  5297. self.cnc_form = self.ui.cncjob_defaults_form
  5298. self.tools_form = self.ui.tools_defaults_form
  5299. self.tools2_form = self.ui.tools2_defaults_form
  5300. self.fa_form = self.ui.util_defaults_form
  5301. try:
  5302. self.ui.general_scroll_area.takeWidget()
  5303. except Exception:
  5304. self.log.debug("Nothing to remove")
  5305. self.ui.general_scroll_area.setWidget(self.gen_form)
  5306. self.gen_form.show()
  5307. try:
  5308. self.ui.gerber_scroll_area.takeWidget()
  5309. except Exception:
  5310. self.log.debug("Nothing to remove")
  5311. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  5312. self.ger_form.show()
  5313. try:
  5314. self.ui.excellon_scroll_area.takeWidget()
  5315. except Exception:
  5316. self.log.debug("Nothing to remove")
  5317. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  5318. self.exc_form.show()
  5319. try:
  5320. self.ui.geometry_scroll_area.takeWidget()
  5321. except Exception:
  5322. self.log.debug("Nothing to remove")
  5323. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  5324. self.geo_form.show()
  5325. try:
  5326. self.ui.cncjob_scroll_area.takeWidget()
  5327. except Exception:
  5328. self.log.debug("Nothing to remove")
  5329. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  5330. self.cnc_form.show()
  5331. try:
  5332. self.ui.tools_scroll_area.takeWidget()
  5333. except Exception:
  5334. self.log.debug("Nothing to remove")
  5335. self.ui.tools_scroll_area.setWidget(self.tools_form)
  5336. self.tools_form.show()
  5337. try:
  5338. self.ui.tools2_scroll_area.takeWidget()
  5339. except Exception:
  5340. self.log.debug("Nothing to remove")
  5341. self.ui.tools2_scroll_area.setWidget(self.tools2_form)
  5342. self.tools2_form.show()
  5343. try:
  5344. self.ui.fa_scroll_area.takeWidget()
  5345. except Exception:
  5346. self.log.debug("Nothing to remove")
  5347. self.ui.fa_scroll_area.setWidget(self.fa_form)
  5348. self.fa_form.show()
  5349. self.log.debug("Finished Preferences GUI form initialization.")
  5350. # self.options2form()
  5351. def init_color_pickers_in_preferences_gui(self):
  5352. # Init Gerber Plot Colors
  5353. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_entry.set_value(self.defaults['gerber_plot_fill'])
  5354. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_button.setStyleSheet(
  5355. "background-color:%s;"
  5356. "border-color: dimgray" % str(self.defaults['gerber_plot_fill'])[:7])
  5357. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_spinner.set_value(
  5358. int(self.defaults['gerber_plot_fill'][7:9], 16))
  5359. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.setValue(
  5360. int(self.defaults['gerber_plot_fill'][7:9], 16))
  5361. self.ui.gerber_defaults_form.gerber_gen_group.pl_color_entry.set_value(self.defaults['gerber_plot_line'])
  5362. self.ui.gerber_defaults_form.gerber_gen_group.pl_color_button.setStyleSheet(
  5363. "background-color:%s;"
  5364. "border-color: dimgray" % str(self.defaults['gerber_plot_line'])[:7])
  5365. # Init Excellon Plot Colors
  5366. self.ui.excellon_defaults_form.excellon_gen_group.fill_color_entry.set_value(
  5367. self.defaults['excellon_plot_fill'])
  5368. self.ui.excellon_defaults_form.excellon_gen_group.fill_color_button.setStyleSheet(
  5369. "background-color:%s;"
  5370. "border-color: dimgray" % str(self.defaults['excellon_plot_fill'])[:7])
  5371. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_spinner.set_value(
  5372. int(self.defaults['excellon_plot_fill'][7:9], 16))
  5373. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.setValue(
  5374. int(self.defaults['excellon_plot_fill'][7:9], 16))
  5375. self.ui.excellon_defaults_form.excellon_gen_group.line_color_entry.set_value(
  5376. self.defaults['excellon_plot_line'])
  5377. self.ui.excellon_defaults_form.excellon_gen_group.line_color_button.setStyleSheet(
  5378. "background-color:%s;"
  5379. "border-color: dimgray" % str(self.defaults['excellon_plot_line'])[:7])
  5380. # Init Geometry Plot Colors
  5381. self.ui.geometry_defaults_form.geometry_gen_group.line_color_entry.set_value(
  5382. self.defaults['geometry_plot_line'])
  5383. self.ui.geometry_defaults_form.geometry_gen_group.line_color_button.setStyleSheet(
  5384. "background-color:%s;"
  5385. "border-color: dimgray" % str(self.defaults['geometry_plot_line'])[:7])
  5386. # Init CNCJob Travel Line Colors
  5387. self.ui.cncjob_defaults_form.cncjob_gen_group.tfill_color_entry.set_value(
  5388. self.defaults['cncjob_travel_fill'])
  5389. self.ui.cncjob_defaults_form.cncjob_gen_group.tfill_color_button.setStyleSheet(
  5390. "background-color:%s;"
  5391. "border-color: dimgray" % str(self.defaults['cncjob_travel_fill'])[:7])
  5392. self.ui.cncjob_defaults_form.cncjob_gen_group.tcolor_alpha_spinner.set_value(
  5393. int(self.defaults['cncjob_travel_fill'][7:9], 16))
  5394. self.ui.cncjob_defaults_form.cncjob_gen_group.tcolor_alpha_slider.setValue(
  5395. int(self.defaults['cncjob_travel_fill'][7:9], 16))
  5396. self.ui.cncjob_defaults_form.cncjob_gen_group.tline_color_entry.set_value(
  5397. self.defaults['cncjob_travel_line'])
  5398. self.ui.cncjob_defaults_form.cncjob_gen_group.tline_color_button.setStyleSheet(
  5399. "background-color:%s;"
  5400. "border-color: dimgray" % str(self.defaults['cncjob_travel_line'])[:7])
  5401. # Init CNCJob Plot Colors
  5402. self.ui.cncjob_defaults_form.cncjob_gen_group.fill_color_entry.set_value(
  5403. self.defaults['cncjob_plot_fill'])
  5404. self.ui.cncjob_defaults_form.cncjob_gen_group.fill_color_button.setStyleSheet(
  5405. "background-color:%s;"
  5406. "border-color: dimgray" % str(self.defaults['cncjob_plot_fill'])[:7])
  5407. self.ui.cncjob_defaults_form.cncjob_gen_group.line_color_entry.set_value(
  5408. self.defaults['cncjob_plot_line'])
  5409. self.ui.cncjob_defaults_form.cncjob_gen_group.line_color_button.setStyleSheet(
  5410. "background-color:%s;"
  5411. "border-color: dimgray" % str(self.defaults['cncjob_plot_line'])[:7])
  5412. # Init Left-Right Selection colors
  5413. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  5414. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5415. "background-color:%s;"
  5416. "border-color: dimgray" % str(self.defaults['global_sel_fill'])[:7])
  5417. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  5418. int(self.defaults['global_sel_fill'][7:9], 16))
  5419. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  5420. int(self.defaults['global_sel_fill'][7:9], 16))
  5421. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  5422. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5423. "background-color:%s;"
  5424. "border-color: dimgray" % str(self.defaults['global_sel_line'])[:7])
  5425. # Init Right-Left Selection colors
  5426. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  5427. self.defaults['global_alt_sel_fill'])
  5428. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5429. "background-color:%s;"
  5430. "border-color: dimgray" % str(self.defaults['global_alt_sel_fill'])[:7])
  5431. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  5432. int(self.defaults['global_sel_fill'][7:9], 16))
  5433. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  5434. int(self.defaults['global_sel_fill'][7:9], 16))
  5435. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  5436. self.defaults['global_alt_sel_line'])
  5437. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5438. "background-color:%s;"
  5439. "border-color: dimgray" % str(self.defaults['global_alt_sel_line'])[:7])
  5440. # Init Draw color and Selection Draw Color
  5441. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  5442. self.defaults['global_draw_color'])
  5443. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5444. "background-color:%s;"
  5445. "border-color: dimgray" % str(self.defaults['global_draw_color'])[:7])
  5446. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  5447. self.defaults['global_sel_draw_color'])
  5448. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5449. "background-color:%s;"
  5450. "border-color: dimgray" % str(self.defaults['global_sel_draw_color'])[:7])
  5451. # Init Project Items color
  5452. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  5453. self.defaults['global_proj_item_color'])
  5454. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5455. "background-color:%s;"
  5456. "border-color: dimgray" % str(self.defaults['global_proj_item_color'])[:7])
  5457. # Init Project Disabled Items color
  5458. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  5459. self.defaults['global_proj_item_dis_color'])
  5460. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5461. "background-color:%s;"
  5462. "border-color: dimgray" % str(self.defaults['global_proj_item_dis_color'])[:7])
  5463. # Init Project Disabled Items color
  5464. self.ui.general_defaults_form.general_app_set_group.mouse_cursor_entry.set_value(
  5465. self.defaults['global_cursor_color'])
  5466. self.ui.general_defaults_form.general_app_set_group.mouse_cursor_button.setStyleSheet(
  5467. "background-color:%s;"
  5468. "border-color: dimgray" % str(self.defaults['global_cursor_color'])[:7])
  5469. # Init the Annotation CNC Job color
  5470. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  5471. self.defaults['cncjob_annotation_fontcolor'])
  5472. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5473. "background-color:%s;"
  5474. "border-color: dimgray" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  5475. # Init the Tool Film color
  5476. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  5477. self.defaults['tools_film_color'])
  5478. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5479. "background-color:%s;"
  5480. "border-color: dimgray" % str(self.defaults['tools_film_color'])[:7]
  5481. )
  5482. # Init the Tool QRCode colors
  5483. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(
  5484. self.defaults['tools_qrcode_fill_color'])
  5485. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5486. "background-color:%s;"
  5487. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])[:7])
  5488. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(
  5489. self.defaults['tools_qrcode_back_color'])
  5490. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5491. "background-color:%s;"
  5492. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])[:7])
  5493. def on_update_exc_export(self, state):
  5494. """
  5495. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  5496. if the update_excellon_cb checkbox is checked
  5497. :param state: state of the checkbox whose signals is tied to his slot
  5498. :return:
  5499. """
  5500. if state:
  5501. # first try to disconnect
  5502. try:
  5503. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.\
  5504. disconnect(self.on_excellon_format_changed)
  5505. except TypeError:
  5506. pass
  5507. try:
  5508. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.\
  5509. disconnect(self.on_excellon_format_changed)
  5510. except TypeError:
  5511. pass
  5512. try:
  5513. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.\
  5514. disconnect(self.on_excellon_format_changed)
  5515. except TypeError:
  5516. pass
  5517. try:
  5518. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.\
  5519. disconnect(self.on_excellon_format_changed)
  5520. except TypeError:
  5521. pass
  5522. try:
  5523. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  5524. disconnect(self.on_excellon_zeros_changed)
  5525. except TypeError:
  5526. pass
  5527. try:
  5528. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  5529. disconnect(self.on_excellon_zeros_changed)
  5530. except TypeError:
  5531. pass
  5532. # the connect them
  5533. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  5534. self.on_excellon_format_changed)
  5535. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  5536. self.on_excellon_format_changed)
  5537. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  5538. self.on_excellon_format_changed)
  5539. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  5540. self.on_excellon_format_changed)
  5541. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  5542. self.on_excellon_zeros_changed)
  5543. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  5544. self.on_excellon_units_changed)
  5545. else:
  5546. # disconnect the signals
  5547. try:
  5548. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  5549. disconnect(self.on_excellon_format_changed)
  5550. except TypeError:
  5551. pass
  5552. try:
  5553. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  5554. disconnect(self.on_excellon_format_changed)
  5555. except TypeError:
  5556. pass
  5557. try:
  5558. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  5559. disconnect(self.on_excellon_format_changed)
  5560. except TypeError:
  5561. pass
  5562. try:
  5563. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  5564. disconnect(self.on_excellon_format_changed)
  5565. except TypeError:
  5566. pass
  5567. try:
  5568. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5569. disconnect(self.on_excellon_zeros_changed)
  5570. except TypeError:
  5571. pass
  5572. try:
  5573. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5574. disconnect(self.on_excellon_zeros_changed)
  5575. except TypeError:
  5576. pass
  5577. def on_excellon_format_changed(self):
  5578. """
  5579. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  5580. :return: None
  5581. """
  5582. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  5583. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5584. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  5585. )
  5586. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5587. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  5588. )
  5589. else:
  5590. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5591. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  5592. )
  5593. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5594. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  5595. )
  5596. def on_excellon_zeros_changed(self):
  5597. """
  5598. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5599. :return: None
  5600. """
  5601. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5602. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5603. )
  5604. def on_excellon_units_changed(self):
  5605. """
  5606. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5607. :return: None
  5608. """
  5609. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5610. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5611. )
  5612. self.on_excellon_format_changed()
  5613. def on_film_color_entry(self):
  5614. self.defaults['tools_film_color'] = \
  5615. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5616. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5617. "background-color:%s;"
  5618. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  5619. )
  5620. def on_film_color_button(self):
  5621. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5622. c_dialog = QtWidgets.QColorDialog()
  5623. film_color = c_dialog.getColor(initial=current_color)
  5624. if film_color.isValid() is False:
  5625. return
  5626. # if new color is different then mark that the Preferences are changed
  5627. if film_color != current_color:
  5628. self.on_preferences_edited()
  5629. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5630. "background-color:%s;"
  5631. "border-color: dimgray" % str(film_color.name())
  5632. )
  5633. new_val_sel = str(film_color.name())
  5634. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5635. self.defaults['tools_film_color'] = new_val_sel
  5636. def on_qrcode_fill_color_entry(self):
  5637. self.defaults['tools_qrcode_fill_color'] = \
  5638. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  5639. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5640. "background-color:%s;"
  5641. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  5642. )
  5643. def on_qrcode_fill_color_button(self):
  5644. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  5645. c_dialog = QtWidgets.QColorDialog()
  5646. fill_color = c_dialog.getColor(initial=current_color)
  5647. if fill_color.isValid() is False:
  5648. return
  5649. # if new color is different then mark that the Preferences are changed
  5650. if fill_color != current_color:
  5651. self.on_preferences_edited()
  5652. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5653. "background-color:%s;"
  5654. "border-color: dimgray" % str(fill_color.name())
  5655. )
  5656. new_val_sel = str(fill_color.name())
  5657. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  5658. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  5659. def on_qrcode_back_color_entry(self):
  5660. self.defaults['tools_qrcode_back_color'] = \
  5661. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  5662. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5663. "background-color:%s;"
  5664. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  5665. )
  5666. def on_qrcode_back_color_button(self):
  5667. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  5668. c_dialog = QtWidgets.QColorDialog()
  5669. back_color = c_dialog.getColor(initial=current_color)
  5670. if back_color.isValid() is False:
  5671. return
  5672. # if new color is different then mark that the Preferences are changed
  5673. if back_color != current_color:
  5674. self.on_preferences_edited()
  5675. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5676. "background-color:%s;"
  5677. "border-color: dimgray" % str(back_color.name())
  5678. )
  5679. new_val_sel = str(back_color.name())
  5680. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  5681. self.defaults['tools_qrcode_back_color'] = new_val_sel
  5682. def on_tab_rmb_click(self, checked):
  5683. self.ui.notebook.set_detachable(val=checked)
  5684. self.defaults["global_tabs_detachable"] = checked
  5685. self.ui.plot_tab_area.set_detachable(val=checked)
  5686. self.defaults["global_tabs_detachable"] = checked
  5687. def on_tab_setup_context_menu(self):
  5688. initial_checked = self.defaults["global_tabs_detachable"]
  5689. action_name = str(_("Detachable Tabs"))
  5690. action = QtWidgets.QAction(self)
  5691. action.setCheckable(True)
  5692. action.setText(action_name)
  5693. action.setChecked(initial_checked)
  5694. self.ui.notebook.tabBar.addAction(action)
  5695. self.ui.plot_tab_area.tabBar.addAction(action)
  5696. try:
  5697. action.triggered.disconnect()
  5698. except TypeError:
  5699. pass
  5700. action.triggered.connect(self.on_tab_rmb_click)
  5701. def on_deselect_all(self):
  5702. self.collection.set_all_inactive()
  5703. self.delete_selection_shape()
  5704. def on_workspace_modified(self):
  5705. # self.save_defaults(silent=True)
  5706. if self.is_legacy is True:
  5707. self.plotcanvas.delete_workspace()
  5708. self.defaults_read_form()
  5709. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5710. def on_workspace(self):
  5711. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  5712. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5713. else:
  5714. self.plotcanvas.delete_workspace()
  5715. self.defaults_read_form()
  5716. # self.save_defaults(silent=True)
  5717. def on_workspace_toggle(self):
  5718. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  5719. try:
  5720. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  5721. except TypeError:
  5722. pass
  5723. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  5724. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  5725. self.on_workspace()
  5726. def on_layout(self, index=None, lay=None):
  5727. """
  5728. Set the toolbars layout (location)
  5729. :param index:
  5730. :param lay: type of layout to be set on the toolbard
  5731. :return: None
  5732. """
  5733. self.report_usage("on_layout()")
  5734. if lay:
  5735. current_layout = lay
  5736. else:
  5737. current_layout = self.ui.general_defaults_form.general_gui_group.layout_combo.get_value()
  5738. lay_settings = QSettings("Open Source", "FlatCAM")
  5739. lay_settings.setValue('layout', current_layout)
  5740. # This will write the setting to the platform specific storage.
  5741. del lay_settings
  5742. # first remove the toolbars:
  5743. try:
  5744. self.ui.removeToolBar(self.ui.toolbarfile)
  5745. self.ui.removeToolBar(self.ui.toolbargeo)
  5746. self.ui.removeToolBar(self.ui.toolbarview)
  5747. self.ui.removeToolBar(self.ui.toolbarshell)
  5748. self.ui.removeToolBar(self.ui.toolbartools)
  5749. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5750. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5751. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5752. self.ui.removeToolBar(self.ui.snap_toolbar)
  5753. self.ui.removeToolBar(self.ui.toolbarshell)
  5754. except Exception:
  5755. pass
  5756. if current_layout == 'standard':
  5757. # ## TOOLBAR INSTALLATION # ##
  5758. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5759. self.ui.toolbarfile.setObjectName('File_TB')
  5760. self.ui.addToolBar(self.ui.toolbarfile)
  5761. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5762. self.ui.toolbargeo.setObjectName('Edit_TB')
  5763. self.ui.addToolBar(self.ui.toolbargeo)
  5764. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5765. self.ui.toolbarview.setObjectName('View_TB')
  5766. self.ui.addToolBar(self.ui.toolbarview)
  5767. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5768. self.ui.toolbarshell.setObjectName('Shell_TB')
  5769. self.ui.addToolBar(self.ui.toolbarshell)
  5770. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5771. self.ui.toolbartools.setObjectName('Tools_TB')
  5772. self.ui.addToolBar(self.ui.toolbartools)
  5773. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5774. # self.ui.exc_edit_toolbar.setVisible(False)
  5775. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5776. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5777. self.ui.addToolBarBreak()
  5778. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5779. # self.ui.geo_edit_toolbar.setVisible(False)
  5780. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5781. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5782. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5783. # self.ui.grb_edit_toolbar.setVisible(False)
  5784. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5785. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5786. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5787. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5788. # self.ui.snap_toolbar.setMaximumHeight(30)
  5789. self.ui.addToolBar(self.ui.snap_toolbar)
  5790. self.ui.corner_snap_btn.setVisible(False)
  5791. self.ui.snap_magnet.setVisible(False)
  5792. elif current_layout == 'compact':
  5793. # ## TOOLBAR INSTALLATION # ##
  5794. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5795. self.ui.toolbarfile.setObjectName('File_TB')
  5796. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5797. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5798. self.ui.toolbargeo.setObjectName('Edit_TB')
  5799. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5800. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5801. self.ui.toolbarshell.setObjectName('Shell_TB')
  5802. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5803. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5804. self.ui.toolbartools.setObjectName('Tools_TB')
  5805. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5806. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5807. # self.ui.geo_edit_toolbar.setVisible(False)
  5808. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5809. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5810. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5811. self.ui.toolbarview.setObjectName('View_TB')
  5812. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5813. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5814. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5815. # self.ui.grb_edit_toolbar.setVisible(False)
  5816. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5817. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5818. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5819. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5820. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5821. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5822. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5823. self.ui.snap_toolbar.setMaximumHeight(30)
  5824. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5825. self.ui.corner_snap_btn.setVisible(True)
  5826. self.ui.snap_magnet.setVisible(True)
  5827. # add all the actions to the toolbars
  5828. self.ui.populate_toolbars()
  5829. # reconnect all the signals to the toolbar actions
  5830. self.connect_toolbar_signals()
  5831. self.ui.grid_snap_btn.setChecked(True)
  5832. self.on_grid_snap_triggered(state=True)
  5833. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5834. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5835. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5836. self.ui.grid_gap_link_cb.setChecked(True)
  5837. def on_cursor_type(self, val):
  5838. """
  5839. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5840. :return: None
  5841. """
  5842. self.app_cursor.enabled = False
  5843. if val == 'small':
  5844. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  5845. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  5846. self.app_cursor = self.plotcanvas.new_cursor()
  5847. else:
  5848. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  5849. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  5850. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5851. if self.ui.grid_snap_btn.isChecked():
  5852. self.app_cursor.enabled = True
  5853. else:
  5854. self.app_cursor.enabled = False
  5855. def on_save_button(self, save_to_file=True):
  5856. log.debug("App.on_save_button() --> Applying preferences to file.")
  5857. # Preferences saved, update flag
  5858. self.preferences_changed_flag = False
  5859. # Preferences save, update the color of the Preferences Tab text
  5860. for idx in range(self.ui.plot_tab_area.count()):
  5861. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5862. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5863. # restore the default stylesheet by setting a blank one
  5864. self.ui.pref_apply_button.setStyleSheet("")
  5865. self.inform.emit('%s' % _("Preferences applied."))
  5866. # make sure we update the self.current_defaults dict used to undo changes to self.defaults
  5867. self.current_defaults.update(self.defaults)
  5868. if save_to_file:
  5869. self.save_defaults(silent=False)
  5870. # load the defaults so they are updated into the app
  5871. self.load_defaults(filename='current_defaults')
  5872. # Re-fresh project options
  5873. self.on_options_app2project()
  5874. settgs = QSettings("Open Source", "FlatCAM")
  5875. # save the notebook font size
  5876. fsize = self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  5877. settgs.setValue('notebook_font_size', fsize)
  5878. # save the axis font size
  5879. g_fsize = self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  5880. settgs.setValue('axis_font_size', g_fsize)
  5881. # save the textbox font size
  5882. tb_fsize = self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  5883. settgs.setValue('textbox_font_size', tb_fsize)
  5884. settgs.setValue(
  5885. 'machinist',
  5886. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  5887. )
  5888. # This will write the setting to the platform specific storage.
  5889. del settgs
  5890. def on_pref_close_button(self):
  5891. # Preferences saved, update flag
  5892. self.preferences_changed_flag = False
  5893. try:
  5894. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_plot_area_tab_closed)
  5895. except TypeError:
  5896. pass
  5897. try:
  5898. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  5899. except (TypeError, AttributeError):
  5900. pass
  5901. self.defaults_write_form(source_dict=self.current_defaults)
  5902. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  5903. lambda: self.on_toggle_units(no_pref=False))
  5904. self.defaults.update(self.current_defaults)
  5905. # shared_items = {k: self.defaults[k] for k in self.defaults if k in self.current_defaults and
  5906. # self.defaults[k] == self.current_defaults[k]}
  5907. # print(len(self.defaults), len(shared_items))
  5908. # Preferences save, update the color of the Preferences Tab text
  5909. for idx in range(self.ui.plot_tab_area.count()):
  5910. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5911. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5912. self.ui.plot_tab_area.closeTab(idx)
  5913. break
  5914. self.inform.emit('%s' % _("Preferences closed without saving."))
  5915. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  5916. def on_tool_add_keypress(self):
  5917. # ## Current application units in Upper Case
  5918. self.units = self.defaults['units'].upper()
  5919. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5920. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5921. if notebook_widget_name == 'selected_tab':
  5922. if self.collection.get_active().kind == 'geometry':
  5923. # Tool add works for Geometry only if Advanced is True in Preferences
  5924. if self.defaults["global_app_level"] == 'a':
  5925. tool_add_popup = FCInputDialog(title="New Tool ...",
  5926. text='Enter a Tool Diameter:',
  5927. min=0.0000, max=99.9999, decimals=4)
  5928. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  5929. val, ok = tool_add_popup.get_value()
  5930. if ok:
  5931. if float(val) == 0:
  5932. self.inform.emit('[WARNING_NOTCL] %s' %
  5933. _("Please enter a tool diameter with non-zero value, in Float format."))
  5934. return
  5935. self.collection.get_active().on_tool_add(dia=float(val))
  5936. else:
  5937. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  5938. else:
  5939. msgbox = QtWidgets.QMessageBox()
  5940. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5941. "Go to Preferences -> General - Show Advanced Options."))
  5942. msgbox.setWindowTitle("Tool adding ...")
  5943. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  5944. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5945. msgbox.setDefaultButton(bt_ok)
  5946. msgbox.exec_()
  5947. # work only if the notebook tab on focus is the Tools_Tab
  5948. if notebook_widget_name == 'tool_tab':
  5949. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5950. # and only if the tool is NCC Tool
  5951. if tool_widget == self.ncclear_tool.toolName:
  5952. self.ncclear_tool.on_add_tool_by_key()
  5953. # and only if the tool is Paint Area Tool
  5954. elif tool_widget == self.paint_tool.toolName:
  5955. self.paint_tool.on_add_tool_by_key()
  5956. # and only if the tool is Solder Paste Dispensing Tool
  5957. elif tool_widget == self.paste_tool.toolName:
  5958. self.paste_tool.on_add_tool_by_key()
  5959. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5960. # See description bellow.
  5961. def on_delete_keypress(self):
  5962. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5963. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5964. if notebook_widget_name == 'selected_tab':
  5965. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5966. self.collection.get_active().on_tool_delete()
  5967. # work only if the notebook tab on focus is the Tools_Tab
  5968. elif notebook_widget_name == 'tool_tab':
  5969. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5970. # and only if the tool is NCC Tool
  5971. if tool_widget == self.ncclear_tool.toolName:
  5972. self.ncclear_tool.on_tool_delete()
  5973. # and only if the tool is Paint Tool
  5974. elif tool_widget == self.paint_tool.toolName:
  5975. self.paint_tool.on_tool_delete()
  5976. # and only if the tool is Solder Paste Dispensing Tool
  5977. elif tool_widget == self.paste_tool.toolName:
  5978. self.paste_tool.on_tool_delete()
  5979. else:
  5980. self.on_delete()
  5981. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5982. # some screens you have to be careful where you hover with your mouse.
  5983. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5984. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5985. # Complicated, I know :)
  5986. def on_delete(self):
  5987. """
  5988. Delete the currently selected FlatCAMObjs.
  5989. :return: None
  5990. """
  5991. self.report_usage("on_delete()")
  5992. response = None
  5993. bt_ok = None
  5994. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5995. # a geometry object before we update it.
  5996. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5997. and self.grb_editor.editor_active is False:
  5998. if self.defaults["global_delete_confirmation"] is True:
  5999. msgbox = QtWidgets.QMessageBox()
  6000. msgbox.setWindowTitle(_("Delete objects"))
  6001. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  6002. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  6003. msgbox.setText(_("Are you sure you want to permanently delete\n"
  6004. "the selected objects?"))
  6005. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6006. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6007. msgbox.setDefaultButton(bt_ok)
  6008. msgbox.exec_()
  6009. response = msgbox.clickedButton()
  6010. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  6011. if self.collection.get_active():
  6012. self.log.debug("App.on_delete()")
  6013. for obj_active in self.collection.get_selected():
  6014. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  6015. if isinstance(obj_active, FlatCAMGerber):
  6016. for el in obj_active.mark_shapes:
  6017. obj_active.mark_shapes[el].clear(update=True)
  6018. obj_active.mark_shapes[el].enabled = False
  6019. # obj_active.mark_shapes[el] = None
  6020. del el
  6021. elif isinstance(obj_active, FlatCAMCNCjob):
  6022. try:
  6023. obj_active.text_col.enabled = False
  6024. del obj_active.text_col
  6025. obj_active.annotation.clear(update=True)
  6026. del obj_active.annotation
  6027. except AttributeError as e:
  6028. log.debug(
  6029. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  6030. )
  6031. while self.collection.get_selected():
  6032. self.delete_first_selected()
  6033. self.inform.emit('%s...' % _("Object(s) deleted"))
  6034. # make sure that the selection shape is deleted, too
  6035. self.delete_selection_shape()
  6036. else:
  6037. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  6038. else:
  6039. self.inform.emit(_("Save the work in Editor and try again ..."))
  6040. def delete_first_selected(self):
  6041. # Keep this for later
  6042. try:
  6043. sel_obj = self.collection.get_active()
  6044. name = sel_obj.options["name"]
  6045. isPlotted = sel_obj.options["plot"]
  6046. except AttributeError:
  6047. self.log.debug("Nothing selected for deletion")
  6048. return
  6049. if self.is_legacy is True:
  6050. # Remove plot only if the object was plotted otherwise delaxes will fail
  6051. if isPlotted:
  6052. try:
  6053. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  6054. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  6055. except Exception as e:
  6056. log.debug("App.delete_first_selected() --> %s" % str(e))
  6057. self.plotcanvas.auto_adjust_axes()
  6058. # Remove from dictionary
  6059. self.collection.delete_active()
  6060. # Clear form
  6061. self.setup_component_editor()
  6062. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  6063. def on_set_origin(self):
  6064. """
  6065. Set the origin to the left mouse click position
  6066. :return: None
  6067. """
  6068. # display the message for the user
  6069. # and ask him to click on the desired position
  6070. self.report_usage("on_set_origin()")
  6071. def origin_replot():
  6072. def worker_task():
  6073. with self.proc_container.new('%s...' % _("Plotting")):
  6074. for obj in self.collection.get_list():
  6075. obj.plot()
  6076. self.plotcanvas.fit_view()
  6077. if self.is_legacy:
  6078. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  6079. else:
  6080. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  6081. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6082. self.inform.emit(_('Click to set the origin ...'))
  6083. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  6084. # first disconnect it as it may have been used by something else
  6085. try:
  6086. self.replot_signal.disconnect()
  6087. except TypeError:
  6088. pass
  6089. self.replot_signal[list].connect(origin_replot)
  6090. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  6091. """
  6092. :param event:
  6093. :param location:
  6094. :param noplot:
  6095. :param use_thread:
  6096. :return:
  6097. """
  6098. noplot_sig = noplot
  6099. def worker_task():
  6100. with self.proc_container.new(_("Setting Origin...")):
  6101. for obj in self.collection.get_list():
  6102. obj.offset((x, y))
  6103. self.object_changed.emit(obj)
  6104. # Update the object bounding box options
  6105. a, b, c, d = obj.bounds()
  6106. obj.options['xmin'] = a
  6107. obj.options['ymin'] = b
  6108. obj.options['xmax'] = c
  6109. obj.options['ymax'] = d
  6110. self.inform.emit('[success] %s...' % _('Origin set'))
  6111. if noplot_sig is False:
  6112. self.replot_signal.emit([])
  6113. if location is not None:
  6114. if len(location) != 2:
  6115. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  6116. return 'fail'
  6117. x, y = location
  6118. if use_thread is True:
  6119. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6120. else:
  6121. worker_task()
  6122. self.should_we_save = True
  6123. return
  6124. if event.button == 1:
  6125. if self.is_legacy is False:
  6126. event_pos = event.pos
  6127. else:
  6128. event_pos = (event.xdata, event.ydata)
  6129. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6130. if self.grid_status():
  6131. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6132. else:
  6133. pos = pos_canvas
  6134. x = 0 - pos[0]
  6135. y = 0 - pos[1]
  6136. if use_thread is True:
  6137. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6138. else:
  6139. worker_task()
  6140. self.should_we_save = True
  6141. def on_move2origin(self, use_thread=True):
  6142. """
  6143. :param event:
  6144. :param location:
  6145. :param noplot:
  6146. :param use_thread:
  6147. :return:
  6148. """
  6149. def worker_task():
  6150. with self.proc_container.new(_("Moving to Origin...")):
  6151. obj_list = self.collection.get_selected()
  6152. if not obj_list:
  6153. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  6154. return
  6155. xminlist = list()
  6156. yminlist = list()
  6157. # first get a bounding box to fit all
  6158. for obj in obj_list:
  6159. xmin, ymin, xmax, ymax = obj.bounds()
  6160. xminlist.append(xmin)
  6161. yminlist.append(ymin)
  6162. # get the minimum x,y for all objects selected
  6163. x = min(xminlist)
  6164. y = min(yminlist)
  6165. for obj in obj_list:
  6166. obj.offset((-x, -y))
  6167. self.object_changed.emit(obj)
  6168. # Update the object bounding box options
  6169. a, b, c, d = obj.bounds()
  6170. obj.options['xmin'] = a
  6171. obj.options['ymin'] = b
  6172. obj.options['xmax'] = c
  6173. obj.options['ymax'] = d
  6174. for obj in obj_list:
  6175. obj.plot()
  6176. self.inform.emit('[success] %s...' % _('Origin set'))
  6177. if use_thread is True:
  6178. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6179. else:
  6180. worker_task()
  6181. self.should_we_save = True
  6182. def on_jump_to(self, custom_location=None, fit_center=True):
  6183. """
  6184. Jump to a location by setting the mouse cursor location
  6185. :return:
  6186. """
  6187. self.report_usage("on_jump_to()")
  6188. if not custom_location:
  6189. dia_box_location = None
  6190. try:
  6191. dia_box_location = eval(self.clipboard.text())
  6192. except Exception:
  6193. pass
  6194. if type(dia_box_location) == tuple:
  6195. dia_box_location = str(dia_box_location)
  6196. else:
  6197. dia_box_location = None
  6198. # dia_box = Dialog_box(title=_("Jump to ..."),
  6199. # label=_("Enter the coordinates in format X,Y:"),
  6200. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6201. # initial_text=dia_box_location)
  6202. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  6203. label=_("Enter the coordinates in format X,Y:"),
  6204. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6205. initial_text=dia_box_location,
  6206. reference=self.defaults['global_jump_ref'])
  6207. if dia_box.ok is True:
  6208. try:
  6209. location = eval(dia_box.location)
  6210. if not isinstance(location, tuple):
  6211. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  6212. return
  6213. if dia_box.reference == 'rel':
  6214. rel_x = self.mouse[0] + location[0]
  6215. rel_y = self.mouse[1] + location[1]
  6216. location = (rel_x, rel_y)
  6217. self.defaults['global_jump_ref'] = dia_box.reference
  6218. except Exception:
  6219. return
  6220. else:
  6221. return
  6222. else:
  6223. location = custom_location
  6224. self.jump_signal.emit(location)
  6225. if fit_center:
  6226. self.plotcanvas.fit_center(loc=location)
  6227. cursor = QtGui.QCursor()
  6228. if self.is_legacy is False:
  6229. # I don't know where those differences come from but they are constant for the current
  6230. # execution of the application and they are multiples of a value around 0.0263mm.
  6231. # In a random way sometimes they are more sometimes they are less
  6232. # if units == 'MM':
  6233. # cal_factor = 0.0263
  6234. # else:
  6235. # cal_factor = 0.0263 / 25.4
  6236. cal_location = (location[0], location[1])
  6237. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6238. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  6239. j_pos = (
  6240. int(canvas_origin.x() + round(jump_loc[0])),
  6241. int(canvas_origin.y() + round(jump_loc[1]))
  6242. )
  6243. cursor.setPos(j_pos[0], j_pos[1])
  6244. else:
  6245. # find the canvas origin which is in the top left corner
  6246. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6247. # determine the coordinates for the lowest left point of the canvas
  6248. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  6249. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  6250. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  6251. # canvas) and the point (width, height) is in the top-right location
  6252. loc = self.plotcanvas.axes.transData.transform_point(location)
  6253. j_pos = (
  6254. int(x0 + loc[0]),
  6255. int(y0 - loc[1])
  6256. )
  6257. cursor.setPos(j_pos[0], j_pos[1])
  6258. self.plotcanvas.mouse = [location[0], location[1]]
  6259. if self.defaults["global_cursor_color_enabled"] is True:
  6260. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  6261. else:
  6262. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  6263. if self.grid_status():
  6264. # Update cursor
  6265. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  6266. symbol='++', edge_color=self.cursor_color_3D,
  6267. edge_width=self.defaults["global_cursor_width"],
  6268. size=self.defaults["global_cursor_size"])
  6269. # Set the position label
  6270. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6271. "<b>Y</b>: %.4f" % (location[0], location[1]))
  6272. # Set the relative position label
  6273. dx = location[0] - float(self.rel_point1[0])
  6274. dy = location[1] - float(self.rel_point1[1])
  6275. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6276. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6277. self.inform.emit('[success] %s' % _("Done."))
  6278. return location
  6279. def on_locate(self, obj, fit_center=True):
  6280. """
  6281. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  6282. :return:
  6283. """
  6284. self.report_usage("on_locate()")
  6285. if obj is None:
  6286. self.inform.emit('[WARNING_NOTCL] %s' % _("There is no object selected..."))
  6287. return 'fail'
  6288. class DialogBoxChoice(QtWidgets.QDialog):
  6289. def __init__(self, title=None, icon=None, choice='bl'):
  6290. """
  6291. :param title: string with the window title
  6292. """
  6293. super(DialogBoxChoice, self).__init__()
  6294. self.ok = False
  6295. self.setWindowIcon(icon)
  6296. self.setWindowTitle(str(title))
  6297. self.form = QtWidgets.QFormLayout(self)
  6298. self.ref_radio = RadioSet([
  6299. {"label": _("Bottom-Left"), "value": "bl"},
  6300. {"label": _("Top-Left"), "value": "tl"},
  6301. {"label": _("Bottom-Right"), "value": "br"},
  6302. {"label": _("Top-Right"), "value": "tr"},
  6303. {"label": _("Center"), "value": "c"}
  6304. ], orientation='vertical', stretch=False)
  6305. self.ref_radio.set_value(choice)
  6306. self.form.addRow(self.ref_radio)
  6307. self.button_box = QtWidgets.QDialogButtonBox(
  6308. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  6309. Qt.Horizontal, parent=self)
  6310. self.form.addRow(self.button_box)
  6311. self.button_box.accepted.connect(self.accept)
  6312. self.button_box.rejected.connect(self.reject)
  6313. if self.exec_() == QtWidgets.QDialog.Accepted:
  6314. self.ok = True
  6315. self.location_point = self.ref_radio.get_value()
  6316. else:
  6317. self.ok = False
  6318. self.location_point = None
  6319. dia_box = DialogBoxChoice(title=_("Locate ..."),
  6320. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  6321. choice=self.defaults['global_locate_pt'])
  6322. if dia_box.ok is True:
  6323. try:
  6324. location_point = dia_box.location_point
  6325. self.defaults['global_locate_pt'] = dia_box.location_point
  6326. except Exception:
  6327. return
  6328. else:
  6329. return
  6330. loc_b = obj.bounds()
  6331. if location_point == 'bl':
  6332. location = (loc_b[0], loc_b[1])
  6333. elif location_point == 'tl':
  6334. location = (loc_b[0], loc_b[3])
  6335. elif location_point == 'br':
  6336. location = (loc_b[2], loc_b[1])
  6337. elif location_point == 'tr':
  6338. location = (loc_b[2], loc_b[3])
  6339. else:
  6340. # center
  6341. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  6342. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  6343. location = (cx, cy)
  6344. self.locate_signal.emit(location, location_point)
  6345. if fit_center:
  6346. self.plotcanvas.fit_center(loc=location)
  6347. cursor = QtGui.QCursor()
  6348. if self.is_legacy is False:
  6349. # I don't know where those differences come from but they are constant for the current
  6350. # execution of the application and they are multiples of a value around 0.0263mm.
  6351. # In a random way sometimes they are more sometimes they are less
  6352. # if units == 'MM':
  6353. # cal_factor = 0.0263
  6354. # else:
  6355. # cal_factor = 0.0263 / 25.4
  6356. cal_location = (location[0], location[1])
  6357. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6358. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  6359. j_pos = (
  6360. int(canvas_origin.x() + round(jump_loc[0])),
  6361. int(canvas_origin.y() + round(jump_loc[1]))
  6362. )
  6363. cursor.setPos(j_pos[0], j_pos[1])
  6364. else:
  6365. # find the canvas origin which is in the top left corner
  6366. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6367. # determine the coordinates for the lowest left point of the canvas
  6368. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  6369. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  6370. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  6371. # canvas) and the point (width, height) is in the top-right location
  6372. loc = self.plotcanvas.axes.transData.transform_point(location)
  6373. j_pos = (
  6374. int(x0 + loc[0]),
  6375. int(y0 - loc[1])
  6376. )
  6377. cursor.setPos(j_pos[0], j_pos[1])
  6378. self.plotcanvas.mouse = [location[0], location[1]]
  6379. if self.defaults["global_cursor_color_enabled"] is True:
  6380. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  6381. else:
  6382. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  6383. if self.grid_status():
  6384. # Update cursor
  6385. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  6386. symbol='++', edge_color=self.cursor_color_3D,
  6387. edge_width=self.defaults["global_cursor_width"],
  6388. size=self.defaults["global_cursor_size"])
  6389. # Set the position label
  6390. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6391. "<b>Y</b>: %.4f" % (location[0], location[1]))
  6392. # Set the relative position label
  6393. dx = location[0] - float(self.rel_point1[0])
  6394. dy = location[1] - float(self.rel_point1[1])
  6395. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6396. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6397. self.inform.emit('[success] %s' % _("Done."))
  6398. return location
  6399. def on_copy_command(self):
  6400. self.report_usage("on_copy_command()")
  6401. def initialize(obj_init, app):
  6402. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6403. try:
  6404. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6405. except AttributeError:
  6406. pass
  6407. try:
  6408. obj_init.apertures = deepcopy(obj.apertures)
  6409. except AttributeError:
  6410. pass
  6411. try:
  6412. if obj.tools:
  6413. obj_init.tools = deepcopy(obj.tools)
  6414. except Exception as e:
  6415. log.debug("App.on_copy_command() --> %s" % str(e))
  6416. try:
  6417. obj_init.source_file = deepcopy(obj.source_file)
  6418. except (AttributeError, TypeError):
  6419. pass
  6420. def initialize_excellon(obj_init, app):
  6421. obj_init.source_file = deepcopy(obj.source_file)
  6422. obj_init.tools = deepcopy(obj.tools)
  6423. # drills are offset, so they need to be deep copied
  6424. obj_init.drills = deepcopy(obj.drills)
  6425. # slots are offset, so they need to be deep copied
  6426. obj_init.slots = deepcopy(obj.slots)
  6427. obj_init.create_geometry()
  6428. def initialize_script(obj_init, app_obj):
  6429. obj_init.source_file = deepcopy(obj.source_file)
  6430. def initialize_document(obj_init, app_obj):
  6431. obj_init.source_file = deepcopy(obj.source_file)
  6432. for obj in self.collection.get_selected():
  6433. obj_name = obj.options["name"]
  6434. try:
  6435. if isinstance(obj, FlatCAMExcellon):
  6436. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  6437. elif isinstance(obj, FlatCAMGerber):
  6438. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  6439. elif isinstance(obj, FlatCAMGeometry):
  6440. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  6441. elif isinstance(obj, FlatCAMScript):
  6442. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  6443. elif isinstance(obj, FlatCAMDocument):
  6444. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  6445. except Exception as e:
  6446. return "Operation failed: %s" % str(e)
  6447. def on_paste_command(self):
  6448. pass
  6449. def on_copy_object2(self, custom_name):
  6450. def initialize_geometry(obj_init, app):
  6451. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6452. try:
  6453. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6454. except AttributeError:
  6455. pass
  6456. try:
  6457. obj_init.apertures = deepcopy(obj.apertures)
  6458. except AttributeError:
  6459. pass
  6460. try:
  6461. if obj.tools:
  6462. obj_init.tools = deepcopy(obj.tools)
  6463. except Exception as ee:
  6464. log.debug("on_copy_object2() --> %s" % str(ee))
  6465. def initialize_gerber(obj_init, app):
  6466. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6467. obj_init.apertures = deepcopy(obj.apertures)
  6468. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  6469. def initialize_excellon(obj_init, app):
  6470. obj_init.tools = deepcopy(obj.tools)
  6471. # drills are offset, so they need to be deep copied
  6472. obj_init.drills = deepcopy(obj.drills)
  6473. # slots are offset, so they need to be deep copied
  6474. obj_init.slots = deepcopy(obj.slots)
  6475. obj_init.create_geometry()
  6476. for obj in self.collection.get_selected():
  6477. obj_name = obj.options["name"]
  6478. try:
  6479. if isinstance(obj, FlatCAMExcellon):
  6480. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  6481. elif isinstance(obj, FlatCAMGerber):
  6482. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  6483. elif isinstance(obj, FlatCAMGeometry):
  6484. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  6485. except Exception as er:
  6486. return "Operation failed: %s" % str(er)
  6487. def on_rename_object(self, text):
  6488. self.report_usage("on_rename_object()")
  6489. named_obj = self.collection.get_active()
  6490. for obj in named_obj:
  6491. if obj is list:
  6492. self.on_rename_object(text)
  6493. else:
  6494. try:
  6495. obj.options['name'] = text
  6496. except Exception as e:
  6497. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  6498. def convert_any2geo(self):
  6499. self.report_usage("convert_any2geo()")
  6500. def initialize(obj_init, app):
  6501. obj_init.solid_geometry = obj.solid_geometry
  6502. try:
  6503. obj_init.follow_geometry = obj.follow_geometry
  6504. except AttributeError:
  6505. pass
  6506. try:
  6507. obj_init.apertures = obj.apertures
  6508. except AttributeError:
  6509. pass
  6510. try:
  6511. if obj.tools:
  6512. obj_init.tools = obj.tools
  6513. except AttributeError:
  6514. pass
  6515. def initialize_excellon(obj_init, app):
  6516. # objs = self.collection.get_selected()
  6517. # FlatCAMGeometry.merge(objs, obj)
  6518. solid_geo = []
  6519. for tool in obj.tools:
  6520. for geo in obj.tools[tool]['solid_geometry']:
  6521. solid_geo.append(geo)
  6522. obj_init.solid_geometry = deepcopy(solid_geo)
  6523. if not self.collection.get_selected():
  6524. log.warning("App.convert_any2geo --> No object selected")
  6525. self.inform.emit('[WARNING_NOTCL] %s' %
  6526. _("No object is selected. Select an object and try again."))
  6527. return
  6528. for obj in self.collection.get_selected():
  6529. obj_name = obj.options["name"]
  6530. try:
  6531. if isinstance(obj, FlatCAMExcellon):
  6532. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  6533. else:
  6534. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  6535. except Exception as e:
  6536. return "Operation failed: %s" % str(e)
  6537. def convert_any2gerber(self):
  6538. self.report_usage("convert_any2gerber()")
  6539. def initialize_geometry(obj_init, app):
  6540. apertures = {}
  6541. apid = 0
  6542. apertures[str(apid)] = {}
  6543. apertures[str(apid)]['geometry'] = []
  6544. for obj_orig in obj.solid_geometry:
  6545. new_elem = dict()
  6546. new_elem['solid'] = obj_orig
  6547. try:
  6548. new_elem['follow'] = obj_orig.exterior
  6549. except AttributeError:
  6550. pass
  6551. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  6552. apertures[str(apid)]['size'] = 0.0
  6553. apertures[str(apid)]['type'] = 'C'
  6554. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6555. obj_init.apertures = deepcopy(apertures)
  6556. def initialize_excellon(obj_init, app):
  6557. apertures = {}
  6558. apid = 10
  6559. for tool in obj.tools:
  6560. apertures[str(apid)] = {}
  6561. apertures[str(apid)]['geometry'] = []
  6562. for geo in obj.tools[tool]['solid_geometry']:
  6563. new_el = dict()
  6564. new_el['solid'] = geo
  6565. new_el['follow'] = geo.exterior
  6566. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6567. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6568. apertures[str(apid)]['type'] = 'C'
  6569. apid += 1
  6570. # create solid_geometry
  6571. solid_geometry = []
  6572. for apid in apertures:
  6573. for geo_el in apertures[apid]['geometry']:
  6574. solid_geometry.append(geo_el['solid'])
  6575. solid_geometry = MultiPolygon(solid_geometry)
  6576. solid_geometry = solid_geometry.buffer(0.0000001)
  6577. obj_init.solid_geometry = deepcopy(solid_geometry)
  6578. obj_init.apertures = deepcopy(apertures)
  6579. # clear the working objects (perhaps not necessary due of Python GC)
  6580. apertures.clear()
  6581. if not self.collection.get_selected():
  6582. log.warning("App.convert_any2gerber --> No object selected")
  6583. self.inform.emit('[WARNING_NOTCL] %s' %
  6584. _("No object is selected. Select an object and try again."))
  6585. return
  6586. for obj in self.collection.get_selected():
  6587. obj_name = obj.options["name"]
  6588. try:
  6589. if isinstance(obj, FlatCAMExcellon):
  6590. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6591. elif isinstance(obj, FlatCAMGeometry):
  6592. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6593. else:
  6594. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6595. except Exception as e:
  6596. return "Operation failed: %s" % str(e)
  6597. def abort_all_tasks(self):
  6598. if self.abort_flag is False:
  6599. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6600. self.abort_flag = True
  6601. def app_is_idle(self):
  6602. if self.abort_flag:
  6603. self.inform.emit('[WARNING_NOTCL] %s' %
  6604. _("The current task was gracefully closed on user request..."))
  6605. self.abort_flag = False
  6606. def on_selectall(self):
  6607. self.report_usage("on_selectall()")
  6608. # delete the possible selection box around a possible selected object
  6609. self.delete_selection_shape()
  6610. for name in self.collection.get_names():
  6611. self.collection.set_active(name)
  6612. curr_sel_obj = self.collection.get_by_name(name)
  6613. # create the selection box around the selected object
  6614. if self.defaults['global_selection_shape'] is True:
  6615. self.draw_selection_shape(curr_sel_obj)
  6616. def on_preferences(self):
  6617. """
  6618. Adds the Preferences in a Tab in Plot Area
  6619. :return:
  6620. """
  6621. # add the tab if it was closed
  6622. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6623. # delete the absolute and relative position and messages in the infobar
  6624. self.ui.position_label.setText("")
  6625. self.ui.rel_position_label.setText("")
  6626. # Switch plot_area to preferences page
  6627. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6628. # self.ui.show()
  6629. # detect changes in the preferences
  6630. for idx in range(self.ui.pref_tab_area.count()):
  6631. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6632. try:
  6633. try:
  6634. tb.textEdited.disconnect(self.on_preferences_edited)
  6635. except (TypeError, AttributeError):
  6636. pass
  6637. tb.textEdited.connect(self.on_preferences_edited)
  6638. except AttributeError:
  6639. pass
  6640. try:
  6641. try:
  6642. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6643. except (TypeError, AttributeError):
  6644. pass
  6645. tb.modificationChanged.connect(self.on_preferences_edited)
  6646. except AttributeError:
  6647. pass
  6648. try:
  6649. try:
  6650. tb.toggled.disconnect(self.on_preferences_edited)
  6651. except (TypeError, AttributeError):
  6652. pass
  6653. tb.toggled.connect(self.on_preferences_edited)
  6654. except AttributeError:
  6655. pass
  6656. try:
  6657. try:
  6658. tb.valueChanged.disconnect(self.on_preferences_edited)
  6659. except (TypeError, AttributeError):
  6660. pass
  6661. tb.valueChanged.connect(self.on_preferences_edited)
  6662. except AttributeError:
  6663. pass
  6664. try:
  6665. try:
  6666. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6667. except (TypeError, AttributeError):
  6668. pass
  6669. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6670. except AttributeError:
  6671. pass
  6672. def on_preferences_edited(self):
  6673. if self.preferences_changed_flag is False:
  6674. self.inform.emit('[WARNING_NOTCL] %s' % _("Preferences edited but not saved."))
  6675. for idx in range(self.ui.plot_tab_area.count()):
  6676. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  6677. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6678. self.ui.pref_apply_button.setStyleSheet("QPushButton {color: red;}")
  6679. self.preferences_changed_flag = True
  6680. def on_tools_database(self):
  6681. """
  6682. Adds the Tools Database in a Tab in Plot Area
  6683. :return:
  6684. """
  6685. for idx in range(self.ui.plot_tab_area.count()):
  6686. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6687. # there can be only one instance of Tools Database at one time
  6688. return
  6689. self.tools_db_tab = ToolsDB(
  6690. app=self,
  6691. parent=self.ui,
  6692. callback_on_edited=self.on_tools_db_edited,
  6693. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  6694. )
  6695. # add the tab if it was closed
  6696. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  6697. self.tools_db_tab.setObjectName("database_tab")
  6698. # delete the absolute and relative position and messages in the infobar
  6699. self.ui.position_label.setText("")
  6700. self.ui.rel_position_label.setText("")
  6701. # Switch plot_area to preferences page
  6702. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  6703. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  6704. self.tools_db_tab.ui_connect()
  6705. def on_tools_db_edited(self):
  6706. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  6707. for idx in range(self.ui.plot_tab_area.count()):
  6708. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6709. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6710. self.tools_db_changed_flag = True
  6711. def on_geometry_tool_add_from_db_executed(self, tool):
  6712. """
  6713. Here add the tool from DB in the selected geometry object
  6714. :return:
  6715. """
  6716. tool_from_db = deepcopy(tool)
  6717. obj = self.collection.get_active()
  6718. if isinstance(obj, FlatCAMGeometry):
  6719. obj.on_tool_from_db_inserted(tool=tool_from_db)
  6720. for idx in range(self.ui.plot_tab_area.count()):
  6721. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6722. wdg = self.ui.plot_tab_area.widget(idx)
  6723. wdg.deleteLater()
  6724. self.ui.plot_tab_area.removeTab(idx)
  6725. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  6726. else:
  6727. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  6728. def on_plot_area_tab_closed(self, title):
  6729. if title == _("Preferences"):
  6730. # disconnect
  6731. for idx in range(self.ui.pref_tab_area.count()):
  6732. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6733. try:
  6734. tb.textEdited.disconnect(self.on_preferences_edited)
  6735. except (TypeError, AttributeError):
  6736. pass
  6737. try:
  6738. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6739. except (TypeError, AttributeError):
  6740. pass
  6741. try:
  6742. tb.toggled.disconnect(self.on_preferences_edited)
  6743. except (TypeError, AttributeError):
  6744. pass
  6745. try:
  6746. tb.valueChanged.disconnect(self.on_preferences_edited)
  6747. except (TypeError, AttributeError):
  6748. pass
  6749. try:
  6750. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6751. except (TypeError, AttributeError):
  6752. pass
  6753. if self.preferences_changed_flag is True:
  6754. msgbox = QtWidgets.QMessageBox()
  6755. msgbox.setText(_("One or more values are changed.\n"
  6756. "Do you want to save the Preferences?"))
  6757. msgbox.setWindowTitle(_("Save Preferences"))
  6758. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6759. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6760. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6761. msgbox.setDefaultButton(bt_yes)
  6762. msgbox.exec_()
  6763. response = msgbox.clickedButton()
  6764. if response == bt_yes:
  6765. self.on_save_button(save_to_file=True)
  6766. self.inform.emit('[success] %s' % _("Preferences saved."))
  6767. else:
  6768. self.preferences_changed_flag = False
  6769. self.inform.emit('')
  6770. return
  6771. if title == _("Tools Database"):
  6772. # disconnect the signals from the table widget in tab
  6773. self.tools_db_tab.ui_disconnect()
  6774. if self.tools_db_changed_flag is True:
  6775. msgbox = QtWidgets.QMessageBox()
  6776. msgbox.setText(_("One or more Tools are edited.\n"
  6777. "Do you want to update the Tools Database?"))
  6778. msgbox.setWindowTitle(_("Save Tools Database"))
  6779. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6780. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6781. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6782. msgbox.setDefaultButton(bt_yes)
  6783. msgbox.exec_()
  6784. response = msgbox.clickedButton()
  6785. if response == bt_yes:
  6786. self.tools_db_tab.on_save_tools_db()
  6787. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  6788. else:
  6789. self.tools_db_changed_flag = False
  6790. self.inform.emit('')
  6791. return
  6792. self.tools_db_tab.deleteLater()
  6793. if title == _("Code Editor"):
  6794. self.toggle_codeeditor = False
  6795. if title == _("Bookmarks Manager"):
  6796. self.book_dialog_tab.rebuild_actions()
  6797. self.book_dialog_tab.deleteLater()
  6798. def on_flipy(self):
  6799. self.report_usage("on_flipy()")
  6800. obj_list = self.collection.get_selected()
  6801. xminlist = []
  6802. yminlist = []
  6803. xmaxlist = []
  6804. ymaxlist = []
  6805. if not obj_list:
  6806. self.inform.emit('[WARNING_NOTCL] %s' %
  6807. _("No object selected to Flip on Y axis."))
  6808. else:
  6809. try:
  6810. # first get a bounding box to fit all
  6811. for obj in obj_list:
  6812. xmin, ymin, xmax, ymax = obj.bounds()
  6813. xminlist.append(xmin)
  6814. yminlist.append(ymin)
  6815. xmaxlist.append(xmax)
  6816. ymaxlist.append(ymax)
  6817. # get the minimum x,y and maximum x,y for all objects selected
  6818. xminimal = min(xminlist)
  6819. yminimal = min(yminlist)
  6820. xmaximal = max(xmaxlist)
  6821. ymaximal = max(ymaxlist)
  6822. px = 0.5 * (xminimal + xmaximal)
  6823. py = 0.5 * (yminimal + ymaximal)
  6824. # execute mirroring
  6825. for obj in obj_list:
  6826. obj.mirror('X', [px, py])
  6827. obj.plot()
  6828. self.object_changed.emit(obj)
  6829. self.inform.emit('[success] %s' %
  6830. _("Flip on Y axis done."))
  6831. except Exception as e:
  6832. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6833. return
  6834. def on_flipx(self):
  6835. self.report_usage("on_flipx()")
  6836. obj_list = self.collection.get_selected()
  6837. xminlist = []
  6838. yminlist = []
  6839. xmaxlist = []
  6840. ymaxlist = []
  6841. if not obj_list:
  6842. self.inform.emit('[WARNING_NOTCL] %s' %
  6843. _("No object selected to Flip on X axis."))
  6844. else:
  6845. try:
  6846. # first get a bounding box to fit all
  6847. for obj in obj_list:
  6848. xmin, ymin, xmax, ymax = obj.bounds()
  6849. xminlist.append(xmin)
  6850. yminlist.append(ymin)
  6851. xmaxlist.append(xmax)
  6852. ymaxlist.append(ymax)
  6853. # get the minimum x,y and maximum x,y for all objects selected
  6854. xminimal = min(xminlist)
  6855. yminimal = min(yminlist)
  6856. xmaximal = max(xmaxlist)
  6857. ymaximal = max(ymaxlist)
  6858. px = 0.5 * (xminimal + xmaximal)
  6859. py = 0.5 * (yminimal + ymaximal)
  6860. # execute mirroring
  6861. for obj in obj_list:
  6862. obj.mirror('Y', [px, py])
  6863. obj.plot()
  6864. self.object_changed.emit(obj)
  6865. self.inform.emit('[success] %s' %
  6866. _("Flip on X axis done."))
  6867. except Exception as e:
  6868. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6869. return
  6870. def on_rotate(self, silent=False, preset=None):
  6871. self.report_usage("on_rotate()")
  6872. obj_list = self.collection.get_selected()
  6873. xminlist = []
  6874. yminlist = []
  6875. xmaxlist = []
  6876. ymaxlist = []
  6877. if not obj_list:
  6878. self.inform.emit('[WARNING_NOTCL] %s' %
  6879. _("No object selected to Rotate."))
  6880. else:
  6881. if silent is False:
  6882. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6883. min=-360, max=360, decimals=4,
  6884. init_val=float(self.defaults['tools_transform_rotate']))
  6885. num, ok = rotatebox.get_value()
  6886. else:
  6887. num = preset
  6888. ok = True
  6889. if ok:
  6890. try:
  6891. # first get a bounding box to fit all
  6892. for obj in obj_list:
  6893. xmin, ymin, xmax, ymax = obj.bounds()
  6894. xminlist.append(xmin)
  6895. yminlist.append(ymin)
  6896. xmaxlist.append(xmax)
  6897. ymaxlist.append(ymax)
  6898. # get the minimum x,y and maximum x,y for all objects selected
  6899. xminimal = min(xminlist)
  6900. yminimal = min(yminlist)
  6901. xmaximal = max(xmaxlist)
  6902. ymaximal = max(ymaxlist)
  6903. px = 0.5 * (xminimal + xmaximal)
  6904. py = 0.5 * (yminimal + ymaximal)
  6905. for sel_obj in obj_list:
  6906. sel_obj.rotate(-float(num), point=(px, py))
  6907. sel_obj.plot()
  6908. self.object_changed.emit(sel_obj)
  6909. self.inform.emit('[success] %s' %
  6910. _("Rotation done."))
  6911. except Exception as e:
  6912. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  6913. return
  6914. def on_skewx(self):
  6915. self.report_usage("on_skewx()")
  6916. obj_list = self.collection.get_selected()
  6917. xminlist = []
  6918. yminlist = []
  6919. if not obj_list:
  6920. self.inform.emit('[WARNING_NOTCL] %s' %
  6921. _("No object selected to Skew/Shear on X axis."))
  6922. else:
  6923. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6924. min=-360, max=360, decimals=4,
  6925. init_val=float(self.defaults['tools_transform_skew_x']))
  6926. num, ok = skewxbox.get_value()
  6927. if ok:
  6928. # first get a bounding box to fit all
  6929. for obj in obj_list:
  6930. xmin, ymin, xmax, ymax = obj.bounds()
  6931. xminlist.append(xmin)
  6932. yminlist.append(ymin)
  6933. # get the minimum x,y and maximum x,y for all objects selected
  6934. xminimal = min(xminlist)
  6935. yminimal = min(yminlist)
  6936. for obj in obj_list:
  6937. obj.skew(num, 0, point=(xminimal, yminimal))
  6938. obj.plot()
  6939. self.object_changed.emit(obj)
  6940. self.inform.emit('[success] %s' %
  6941. _("Skew on X axis done."))
  6942. def on_skewy(self):
  6943. self.report_usage("on_skewy()")
  6944. obj_list = self.collection.get_selected()
  6945. xminlist = []
  6946. yminlist = []
  6947. if not obj_list:
  6948. self.inform.emit('[WARNING_NOTCL] %s' %
  6949. _("No object selected to Skew/Shear on Y axis."))
  6950. else:
  6951. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6952. min=-360, max=360, decimals=4,
  6953. init_val=float(self.defaults['tools_transform_skew_y']))
  6954. num, ok = skewybox.get_value()
  6955. if ok:
  6956. # first get a bounding box to fit all
  6957. for obj in obj_list:
  6958. xmin, ymin, xmax, ymax = obj.bounds()
  6959. xminlist.append(xmin)
  6960. yminlist.append(ymin)
  6961. # get the minimum x,y and maximum x,y for all objects selected
  6962. xminimal = min(xminlist)
  6963. yminimal = min(yminlist)
  6964. for obj in obj_list:
  6965. obj.skew(0, num, point=(xminimal, yminimal))
  6966. obj.plot()
  6967. self.object_changed.emit(obj)
  6968. self.inform.emit('[success] %s' %
  6969. _("Skew on Y axis done."))
  6970. def on_plots_updated(self):
  6971. """
  6972. Callback used to report when the plots have changed.
  6973. Adjust axes and zooms to fit.
  6974. :return: None
  6975. """
  6976. if self.is_legacy is False:
  6977. self.plotcanvas.update() # TODO: Need update canvas?
  6978. else:
  6979. self.plotcanvas.auto_adjust_axes()
  6980. self.on_zoom_fit(None)
  6981. self.collection.update_view()
  6982. # self.inform.emit(_("Plots updated ..."))
  6983. # TODO: Rework toolbar 'clear', 'replot' functions
  6984. def on_toolbar_replot(self):
  6985. """
  6986. Callback for toolbar button. Re-plots all objects.
  6987. :return: None
  6988. """
  6989. self.report_usage("on_toolbar_replot")
  6990. self.log.debug("on_toolbar_replot()")
  6991. try:
  6992. self.collection.get_active().read_form()
  6993. except AttributeError:
  6994. self.log.debug("on_toolbar_replot(): AttributeError")
  6995. pass
  6996. self.plot_all()
  6997. def on_row_activated(self, index):
  6998. if index.isValid():
  6999. if index.internalPointer().parent_item != self.collection.root_item:
  7000. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7001. self.collection.on_item_activated(index)
  7002. def on_row_selected(self, obj_name):
  7003. # this is a special string; when received it will make all entries unchecked
  7004. # it mean we clicked outside of the items and deselected all
  7005. if obj_name == 'none':
  7006. for act in self.ui.menuobjects.actions():
  7007. act.setChecked(False)
  7008. return
  7009. # get the name of the selected objects and add them to a list
  7010. name_list = list()
  7011. for obj in self.collection.get_selected():
  7012. name_list.append(obj.options['name'])
  7013. # set all actions as unchecked but the ones selected make them checked
  7014. for act in self.ui.menuobjects.actions():
  7015. act.setChecked(False)
  7016. if act.text() in name_list:
  7017. act.setChecked(True)
  7018. def on_collection_updated(self, obj, state, old_name):
  7019. """
  7020. Create a menu from the object loaded in the collection.
  7021. TODO: should use the collection model to do this
  7022. :param obj: object that was changd (added, deleted, renamed)
  7023. :param state: what was done with the objectCand be: added, deleted, delete_all, renamed
  7024. :param old_name: the old name of the object before the action that triggered this slot happened
  7025. :return: None
  7026. """
  7027. icon_files = {
  7028. "gerber": self.resource_location + "/flatcam_icon16.png",
  7029. "excellon": self.resource_location + "/drill16.png",
  7030. "cncjob": self.resource_location + "/cnc16.png",
  7031. "geometry": self.resource_location + "/geometry16.png",
  7032. "script": self.resource_location + "/script_new16.png",
  7033. "document": self.resource_location + "/notes16_1.png"
  7034. }
  7035. if state == 'append':
  7036. for act in self.ui.menuobjects.actions():
  7037. try:
  7038. act.triggered.disconnect()
  7039. except TypeError:
  7040. pass
  7041. self.ui.menuobjects.clear()
  7042. gerber_list = list()
  7043. exc_list = list()
  7044. cncjob_list = list()
  7045. geo_list = list()
  7046. script_list = list()
  7047. doc_list = list()
  7048. for name in self.collection.get_names():
  7049. obj_named = self.collection.get_by_name(name)
  7050. if obj_named.kind == 'gerber':
  7051. gerber_list.append(name)
  7052. elif obj_named.kind == 'excellon':
  7053. exc_list.append(name)
  7054. elif obj_named.kind == 'cncjob':
  7055. cncjob_list.append(name)
  7056. elif obj_named.kind == 'geometry':
  7057. geo_list.append(name)
  7058. elif obj_named.kind == 'script':
  7059. script_list.append(name)
  7060. elif obj_named.kind == 'document':
  7061. doc_list.append(name)
  7062. def add_act(o_name):
  7063. obj_for_icon = self.collection.get_by_name(o_name)
  7064. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  7065. add_action.setCheckable(True)
  7066. add_action.setText(o_name)
  7067. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  7068. add_action.triggered.connect(
  7069. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  7070. self.collection.set_inactive(o_name))
  7071. self.ui.menuobjects.addAction(add_action)
  7072. for name in gerber_list:
  7073. add_act(name)
  7074. self.ui.menuobjects.addSeparator()
  7075. for name in exc_list:
  7076. add_act(name)
  7077. self.ui.menuobjects.addSeparator()
  7078. for name in cncjob_list:
  7079. add_act(name)
  7080. self.ui.menuobjects.addSeparator()
  7081. for name in geo_list:
  7082. add_act(name)
  7083. self.ui.menuobjects.addSeparator()
  7084. for name in script_list:
  7085. add_act(name)
  7086. self.ui.menuobjects.addSeparator()
  7087. for name in doc_list:
  7088. add_act(name)
  7089. self.ui.menuobjects.addSeparator()
  7090. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  7091. QtGui.QIcon(self.resource_location + '/select_all.png'),
  7092. _('Select All')
  7093. )
  7094. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  7095. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  7096. _('Deselect All')
  7097. )
  7098. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  7099. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  7100. elif state == 'delete':
  7101. for act in self.ui.menuobjects.actions():
  7102. if act.text() == obj.options['name']:
  7103. try:
  7104. act.triggered.disconnect()
  7105. except TypeError:
  7106. pass
  7107. self.ui.menuobjects.removeAction(act)
  7108. break
  7109. elif state == 'rename':
  7110. for act in self.ui.menuobjects.actions():
  7111. if act.text() == old_name:
  7112. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  7113. add_action.setText(obj.options['name'])
  7114. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  7115. add_action.triggered.connect(
  7116. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  7117. self.collection.set_inactive(obj.options['name']))
  7118. self.ui.menuobjects.insertAction(act, add_action)
  7119. try:
  7120. act.triggered.disconnect()
  7121. except TypeError:
  7122. pass
  7123. self.ui.menuobjects.removeAction(act)
  7124. break
  7125. elif state == 'delete_all':
  7126. for act in self.ui.menuobjects.actions():
  7127. try:
  7128. act.triggered.disconnect()
  7129. except TypeError:
  7130. pass
  7131. self.ui.menuobjects.clear()
  7132. self.ui.menuobjects.addSeparator()
  7133. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  7134. QtGui.QIcon(self.resource_location + '/select_all.png'),
  7135. _('Select All')
  7136. )
  7137. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  7138. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  7139. _('Deselect All')
  7140. )
  7141. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  7142. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  7143. def on_objects_selection(self, on_off):
  7144. obj_list = self.collection.get_names()
  7145. if on_off is True:
  7146. self.collection.set_all_active()
  7147. for act in self.ui.menuobjects.actions():
  7148. try:
  7149. act.setChecked(True)
  7150. except Exception:
  7151. pass
  7152. if obj_list:
  7153. self.inform.emit('[selected] %s' % _("All objects are selected."))
  7154. else:
  7155. self.collection.set_all_inactive()
  7156. for act in self.ui.menuobjects.actions():
  7157. try:
  7158. act.setChecked(False)
  7159. except Exception:
  7160. pass
  7161. if obj_list:
  7162. self.inform.emit('%s' % _("Objects selection is cleared."))
  7163. else:
  7164. self.inform.emit('')
  7165. def grid_status(self):
  7166. if self.ui.grid_snap_btn.isChecked():
  7167. return True
  7168. else:
  7169. return False
  7170. def populate_cmenu_grids(self):
  7171. units = self.defaults['units'].lower()
  7172. for act in self.ui.cmenu_gridmenu.actions():
  7173. act.triggered.disconnect()
  7174. self.ui.cmenu_gridmenu.clear()
  7175. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  7176. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  7177. _("Grid On/Off"))
  7178. grid_toggle.setCheckable(True)
  7179. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  7180. self.ui.cmenu_gridmenu.addSeparator()
  7181. for grid in sorted_list:
  7182. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  7183. "%s" % str(grid))
  7184. action.triggered.connect(self.set_grid)
  7185. self.ui.cmenu_gridmenu.addSeparator()
  7186. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  7187. _("Add"))
  7188. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  7189. _("Delete"))
  7190. grid_add.triggered.connect(self.on_grid_add)
  7191. grid_delete.triggered.connect(self.on_grid_delete)
  7192. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  7193. def set_grid(self):
  7194. self.ui.grid_gap_x_entry.setText(self.sender().text())
  7195. self.ui.grid_gap_y_entry.setText(self.sender().text())
  7196. def on_grid_add(self):
  7197. # ## Current application units in lower Case
  7198. units = self.defaults['units'].lower()
  7199. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  7200. text=_('Enter a Grid Value:'),
  7201. min=0.0000, max=99.9999, decimals=4)
  7202. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  7203. val, ok = grid_add_popup.get_value()
  7204. if ok:
  7205. if float(val) == 0:
  7206. self.inform.emit('[WARNING_NOTCL] %s' %
  7207. _("Please enter a grid value with non-zero value, in Float format."))
  7208. return
  7209. else:
  7210. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  7211. self.defaults["global_grid_context_menu"][str(units)].append(val)
  7212. self.inform.emit('[success] %s...' %
  7213. _("New Grid added"))
  7214. else:
  7215. self.inform.emit('[WARNING_NOTCL] %s...' %
  7216. _("Grid already exists"))
  7217. else:
  7218. self.inform.emit('[WARNING_NOTCL] %s...' %
  7219. _("Adding New Grid cancelled"))
  7220. def on_grid_delete(self):
  7221. # ## Current application units in lower Case
  7222. units = self.defaults['units'].lower()
  7223. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  7224. text='Enter a Grid Value:',
  7225. min=0.0000, max=99.9999, decimals=4)
  7226. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  7227. val, ok = grid_del_popup.get_value()
  7228. if ok:
  7229. if float(val) == 0:
  7230. self.inform.emit('[WARNING_NOTCL] %s' %
  7231. _("Please enter a grid value with non-zero value, in Float format."))
  7232. return
  7233. else:
  7234. try:
  7235. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  7236. except ValueError:
  7237. self.inform.emit('[ERROR_NOTCL]%s...' %
  7238. _(" Grid Value does not exist"))
  7239. return
  7240. self.inform.emit('[success] %s...' %
  7241. _("Grid Value deleted"))
  7242. else:
  7243. self.inform.emit('[WARNING_NOTCL] %s...' %
  7244. _("Delete Grid value cancelled"))
  7245. def on_shortcut_list(self):
  7246. self.report_usage("on_shortcut_list()")
  7247. # add the tab if it was closed
  7248. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  7249. # delete the absolute and relative position and messages in the infobar
  7250. self.ui.position_label.setText("")
  7251. self.ui.rel_position_label.setText("")
  7252. # Switch plot_area to preferences page
  7253. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  7254. # self.ui.show()
  7255. def on_select_tab(self, name):
  7256. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  7257. if self.ui.splitter.sizes()[0] == 0:
  7258. self.ui.splitter.setSizes([1, 1])
  7259. else:
  7260. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  7261. self.ui.splitter.setSizes([0, 1])
  7262. if name == 'project':
  7263. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7264. elif name == 'selected':
  7265. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7266. elif name == 'tool':
  7267. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  7268. def on_copy_name(self):
  7269. self.report_usage("on_copy_name()")
  7270. obj = self.collection.get_active()
  7271. try:
  7272. name = obj.options["name"]
  7273. except AttributeError:
  7274. log.debug("on_copy_name() --> No object selected to copy it's name")
  7275. self.inform.emit('[WARNING_NOTCL]%s' %
  7276. _(" No object selected to copy it's name"))
  7277. return
  7278. self.clipboard.setText(name)
  7279. self.inform.emit(_("Name copied on clipboard ..."))
  7280. def on_mouse_click_over_plot(self, event):
  7281. """
  7282. Default actions are:
  7283. :param event: Contains information about the event, like which button
  7284. was clicked, the pixel coordinates and the axes coordinates.
  7285. :return: None
  7286. """
  7287. self.pos = list()
  7288. if self.is_legacy is False:
  7289. event_pos = event.pos
  7290. pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  7291. # Set the mouse button for panning
  7292. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7293. else:
  7294. event_pos = (event.xdata, event.ydata)
  7295. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7296. pan_button = 3 if self.defaults["global_pan_button"] == '2'else 2
  7297. # So it can receive key presses
  7298. self.plotcanvas.native.setFocus()
  7299. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7300. if self.grid_status() == True:
  7301. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  7302. else:
  7303. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  7304. try:
  7305. if event.button == 1:
  7306. # Reset here the relative coordinates so there is a new reference on the click position
  7307. if self.rel_point1 is None:
  7308. self.rel_point1 = self.pos
  7309. else:
  7310. self.rel_point2 = copy(self.rel_point1)
  7311. self.rel_point1 = self.pos
  7312. self.on_mouse_move_over_plot(event, origin_click=True)
  7313. except Exception as e:
  7314. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  7315. def on_mouse_double_click_over_plot(self, event):
  7316. if event.button == 1:
  7317. self.doubleclick = True
  7318. def on_mouse_move_over_plot(self, event, origin_click=None):
  7319. """
  7320. Callback for the mouse motion event over the plot.
  7321. :param event: Contains information about the event.
  7322. :param origin_click
  7323. :return: None
  7324. """
  7325. if self.is_legacy is False:
  7326. event_pos = event.pos
  7327. if self.defaults["global_pan_button"] == '2':
  7328. pan_button = 2
  7329. else:
  7330. pan_button = 3
  7331. self.event_is_dragging = event.is_dragging
  7332. else:
  7333. event_pos = (event.xdata, event.ydata)
  7334. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7335. if self.defaults["global_pan_button"] == '2':
  7336. pan_button = 3
  7337. else:
  7338. pan_button = 2
  7339. self.event_is_dragging = self.plotcanvas.is_dragging
  7340. # So it can receive key presses
  7341. self.plotcanvas.native.setFocus()
  7342. self.pos_jump = event_pos
  7343. self.ui.popMenu.mouse_is_panning = False
  7344. if not origin_click:
  7345. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  7346. if event.button == pan_button and self.event_is_dragging == 1:
  7347. self.ui.popMenu.mouse_is_panning = True
  7348. return
  7349. if self.rel_point1 is not None:
  7350. try: # May fail in case mouse not within axes
  7351. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7352. if self.grid_status():
  7353. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7354. # Update cursor
  7355. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  7356. symbol='++', edge_color=self.cursor_color_3D,
  7357. edge_width=self.defaults["global_cursor_width"],
  7358. size=self.defaults["global_cursor_size"])
  7359. else:
  7360. pos = (pos_canvas[0], pos_canvas[1])
  7361. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  7362. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  7363. dx = pos[0] - float(self.rel_point1[0])
  7364. dy = pos[1] - float(self.rel_point1[1])
  7365. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  7366. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  7367. self.mouse = [pos[0], pos[1]]
  7368. # if the mouse is moved and the LMB is clicked then the action is a selection
  7369. if self.event_is_dragging == 1 and event.button == 1:
  7370. self.delete_selection_shape()
  7371. if dx < 0:
  7372. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  7373. face_color=self.defaults['global_alt_sel_fill'])
  7374. self.selection_type = False
  7375. elif dx >= 0:
  7376. self.draw_moving_selection_shape(self.pos, pos)
  7377. self.selection_type = True
  7378. else:
  7379. self.selection_type = None
  7380. # hover effect - enabled in Preferences -> General -> GUI Settings
  7381. if self.defaults['global_hover']:
  7382. for obj in self.collection.get_list():
  7383. try:
  7384. # select the object(s) only if it is enabled (plotted)
  7385. if obj.options['plot']:
  7386. if obj not in self.collection.get_selected():
  7387. poly_obj = Polygon(
  7388. [(obj.options['xmin'], obj.options['ymin']),
  7389. (obj.options['xmax'], obj.options['ymin']),
  7390. (obj.options['xmax'], obj.options['ymax']),
  7391. (obj.options['xmin'], obj.options['ymax'])]
  7392. )
  7393. if Point(pos).within(poly_obj):
  7394. if obj.isHovering is False:
  7395. obj.isHovering = True
  7396. obj.notHovering = True
  7397. # create the selection box around the selected object
  7398. self.draw_hover_shape(obj, color='#d1e0e0FF')
  7399. else:
  7400. if obj.notHovering is True:
  7401. obj.notHovering = False
  7402. obj.isHovering = False
  7403. self.delete_hover_shape()
  7404. except Exception:
  7405. # the Exception here will happen if we try to select on screen and we have an
  7406. # newly (and empty) just created Geometry or Excellon object that do not have the
  7407. # xmin, xmax, ymin, ymax options.
  7408. # In this case poly_obj creation (see above) will fail
  7409. pass
  7410. except Exception:
  7411. self.ui.position_label.setText("")
  7412. self.ui.rel_position_label.setText("")
  7413. self.mouse = None
  7414. def on_mouse_click_release_over_plot(self, event):
  7415. """
  7416. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  7417. and has been registered in ''self.__init__()''.
  7418. :param event: contains information about the event.
  7419. :return:
  7420. """
  7421. if self.is_legacy is False:
  7422. event_pos = event.pos
  7423. right_button = 2
  7424. else:
  7425. event_pos = (event.xdata, event.ydata)
  7426. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7427. right_button = 3
  7428. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7429. if self.grid_status():
  7430. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7431. else:
  7432. pos = (pos_canvas[0], pos_canvas[1])
  7433. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  7434. # canvas menu
  7435. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  7436. self.cursor = QtGui.QCursor()
  7437. self.populate_cmenu_grids()
  7438. self.ui.popMenu.popup(self.cursor.pos())
  7439. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  7440. # selection and then select a type of selection ("enclosing" or "touching")
  7441. if event.button == 1: # left click
  7442. modifiers = QtWidgets.QApplication.keyboardModifiers()
  7443. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  7444. if modifiers == QtCore.Qt.ShiftModifier:
  7445. # do not auto open the Project Tab
  7446. self.click_noproject = True
  7447. self.clipboard.setText(
  7448. self.defaults["global_point_clipboard_format"] %
  7449. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  7450. )
  7451. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  7452. return
  7453. if self.doubleclick is True:
  7454. self.doubleclick = False
  7455. if self.collection.get_selected():
  7456. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7457. if self.ui.splitter.sizes()[0] == 0:
  7458. self.ui.splitter.setSizes([1, 1])
  7459. try:
  7460. # delete the selection shape(S) as it may be in the way
  7461. self.delete_selection_shape()
  7462. self.delete_hover_shape()
  7463. except Exception as e:
  7464. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  7465. return
  7466. else:
  7467. if self.selection_type is not None:
  7468. try:
  7469. self.selection_area_handler(self.pos, pos, self.selection_type)
  7470. self.selection_type = None
  7471. except Exception as e:
  7472. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  7473. return
  7474. else:
  7475. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  7476. if key_modifier == QtCore.Qt.ShiftModifier:
  7477. mod_key = 'Shift'
  7478. elif key_modifier == QtCore.Qt.ControlModifier:
  7479. mod_key = 'Control'
  7480. else:
  7481. mod_key = None
  7482. try:
  7483. if mod_key == self.defaults["global_mselect_key"]:
  7484. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  7485. # deselect, and if it's not selected then it will be selected
  7486. # If there is no active command (self.command_active is None) then we check if we clicked
  7487. # on a object by checking the bounding limits against mouse click position
  7488. if self.command_active is None:
  7489. self.select_objects(key='CTRL')
  7490. self.delete_hover_shape()
  7491. else:
  7492. # If there is no active command (self.command_active is None) then we check if we clicked
  7493. # on a object by checking the bounding limits against mouse click position
  7494. if self.command_active is None:
  7495. self.select_objects()
  7496. self.delete_hover_shape()
  7497. except Exception as e:
  7498. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  7499. return
  7500. def selection_area_handler(self, start_pos, end_pos, sel_type):
  7501. """
  7502. :param start_pos: mouse position when the selection LMB click was done
  7503. :param end_pos: mouse position when the left mouse button is released
  7504. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  7505. :return:
  7506. """
  7507. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  7508. # delete previous selection shape
  7509. self.delete_selection_shape()
  7510. # make all objects inactive
  7511. self.collection.set_all_inactive()
  7512. for obj in self.collection.get_list():
  7513. try:
  7514. # select the object(s) only if it is enabled (plotted)
  7515. if obj.options['plot']:
  7516. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  7517. (obj.options['xmax'], obj.options['ymin']),
  7518. (obj.options['xmax'], obj.options['ymax']),
  7519. (obj.options['xmin'], obj.options['ymax'])])
  7520. if sel_type is True:
  7521. if poly_obj.within(poly_selection):
  7522. # create the selection box around the selected object
  7523. if self.defaults['global_selection_shape'] is True:
  7524. self.draw_selection_shape(obj)
  7525. self.collection.set_active(obj.options['name'])
  7526. else:
  7527. if poly_selection.intersects(poly_obj):
  7528. # create the selection box around the selected object
  7529. if self.defaults['global_selection_shape'] is True:
  7530. self.draw_selection_shape(obj)
  7531. self.collection.set_active(obj.options['name'])
  7532. obj.selection_shape_drawn = True
  7533. except Exception as e:
  7534. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  7535. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  7536. # In this case poly_obj creation (see above) will fail
  7537. log.debug("App.selection_area_handler() --> %s" % str(e))
  7538. def select_objects(self, key=None):
  7539. """
  7540. Will select objects clicked on canvas
  7541. :param key: for future use in cumulative selection
  7542. :return:
  7543. """
  7544. # list where we store the overlapped objects under our mouse left click position
  7545. objects_under_the_click_list = []
  7546. # Populate the list with the overlapped objects on the click position
  7547. curr_x, curr_y = self.pos
  7548. for obj in self.all_objects_list:
  7549. # FlatCAMScript and FlatCAMDocument objects can't be selected
  7550. if isinstance(obj, FlatCAMScript) or isinstance(obj, FlatCAMDocument):
  7551. continue
  7552. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  7553. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  7554. if obj.options['name'] not in objects_under_the_click_list:
  7555. if obj.options['plot']:
  7556. # add objects to the objects_under_the_click list only if the object is plotted
  7557. # (active and not disabled)
  7558. objects_under_the_click_list.append(obj.options['name'])
  7559. try:
  7560. if objects_under_the_click_list:
  7561. curr_sel_obj = self.collection.get_active()
  7562. # case when there is only an object under the click and we toggle it
  7563. if len(objects_under_the_click_list) == 1:
  7564. if curr_sel_obj is None:
  7565. self.collection.set_active(objects_under_the_click_list[0])
  7566. curr_sel_obj = self.collection.get_active()
  7567. # create the selection box around the selected object
  7568. if self.defaults['global_selection_shape'] is True:
  7569. self.draw_selection_shape(curr_sel_obj)
  7570. curr_sel_obj.selection_shape_drawn = True
  7571. elif curr_sel_obj.options['name'] not in objects_under_the_click_list:
  7572. self.on_objects_selection(False)
  7573. self.delete_selection_shape()
  7574. curr_sel_obj.selection_shape_drawn = False
  7575. self.collection.set_active(objects_under_the_click_list[0])
  7576. curr_sel_obj = self.collection.get_active()
  7577. # create the selection box around the selected object
  7578. if self.defaults['global_selection_shape'] is True:
  7579. self.draw_selection_shape(curr_sel_obj)
  7580. curr_sel_obj.selection_shape_drawn = True
  7581. self.selected_message(curr_sel_obj=curr_sel_obj)
  7582. elif curr_sel_obj.selection_shape_drawn is False:
  7583. if self.defaults['global_selection_shape'] is True:
  7584. self.draw_selection_shape(curr_sel_obj)
  7585. curr_sel_obj.selection_shape_drawn = True
  7586. else:
  7587. self.on_objects_selection(False)
  7588. self.delete_selection_shape()
  7589. if self.call_source != 'app':
  7590. self.call_source = 'app'
  7591. self.selected_message(curr_sel_obj=curr_sel_obj)
  7592. else:
  7593. # If there is no selected object
  7594. # make active the first element of the overlapped objects list
  7595. if self.collection.get_active() is None:
  7596. self.collection.set_active(objects_under_the_click_list[0])
  7597. self.collection.get_by_name(objects_under_the_click_list[0]).selection_shape_drawn = True
  7598. name_sel_obj = self.collection.get_active().options['name']
  7599. # In case that there is a selected object but it is not in the overlapped object list
  7600. # make that object inactive and activate the first element in the overlapped object list
  7601. if name_sel_obj not in objects_under_the_click_list:
  7602. self.collection.set_inactive(name_sel_obj)
  7603. name_sel_obj = objects_under_the_click_list[0]
  7604. self.collection.set_active(name_sel_obj)
  7605. else:
  7606. sel_idx = objects_under_the_click_list.index(name_sel_obj)
  7607. self.collection.set_all_inactive()
  7608. self.collection.set_active(objects_under_the_click_list[(sel_idx + 1) %
  7609. len(objects_under_the_click_list)])
  7610. curr_sel_obj = self.collection.get_active()
  7611. # delete the possible selection box around a possible selected object
  7612. self.delete_selection_shape()
  7613. curr_sel_obj.selection_shape_drawn = False
  7614. # create the selection box around the selected object
  7615. if self.defaults['global_selection_shape'] is True:
  7616. self.draw_selection_shape(curr_sel_obj)
  7617. curr_sel_obj.selection_shape_drawn = True
  7618. self.selected_message(curr_sel_obj=curr_sel_obj)
  7619. else:
  7620. # deselect everything
  7621. self.on_objects_selection(False)
  7622. # delete the possible selection box around a possible selected object
  7623. self.delete_selection_shape()
  7624. for o in self.collection.get_list():
  7625. o.selection_shape_drawn = False
  7626. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  7627. # only when working on App
  7628. if self.call_source == 'app':
  7629. if self.click_noproject is False:
  7630. # if the Tool Tab is in focus don't change focus to Project Tab
  7631. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  7632. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7633. else:
  7634. # restore auto open the Project Tab
  7635. self.click_noproject = False
  7636. # delete any text in the status bar, implicitly the last object name that was selected
  7637. # self.inform.emit("")
  7638. else:
  7639. self.call_source = 'app'
  7640. except Exception as e:
  7641. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  7642. def selected_message(self, curr_sel_obj):
  7643. if curr_sel_obj:
  7644. if curr_sel_obj.kind == 'gerber':
  7645. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7646. color='green',
  7647. name=str(curr_sel_obj.options['name']),
  7648. tx=_("selected"))
  7649. )
  7650. elif curr_sel_obj.kind == 'excellon':
  7651. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7652. color='brown',
  7653. name=str(curr_sel_obj.options['name']),
  7654. tx=_("selected"))
  7655. )
  7656. elif curr_sel_obj.kind == 'cncjob':
  7657. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7658. color='blue',
  7659. name=str(curr_sel_obj.options['name']),
  7660. tx=_("selected"))
  7661. )
  7662. elif curr_sel_obj.kind == 'geometry':
  7663. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7664. color='red',
  7665. name=str(curr_sel_obj.options['name']),
  7666. tx=_("selected"))
  7667. )
  7668. def delete_hover_shape(self):
  7669. self.hover_shapes.clear()
  7670. self.hover_shapes.redraw()
  7671. def draw_hover_shape(self, sel_obj, color=None):
  7672. """
  7673. :param sel_obj: the object for which the hover shape must be drawn
  7674. :return:
  7675. """
  7676. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7677. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7678. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7679. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7680. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  7681. if self.defaults['units'].upper() == 'MM':
  7682. hover_rect = hover_rect.buffer(-0.1)
  7683. hover_rect = hover_rect.buffer(0.2)
  7684. else:
  7685. hover_rect = hover_rect.buffer(-0.00393)
  7686. hover_rect = hover_rect.buffer(0.00787)
  7687. # if color:
  7688. # face = Color(color)
  7689. # face.alpha = 0.2
  7690. # outline = Color(color, alpha=0.8)
  7691. # else:
  7692. # face = Color(self.defaults['global_sel_fill'])
  7693. # face.alpha = 0.2
  7694. # outline = self.defaults['global_sel_line']
  7695. if color:
  7696. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7697. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7698. else:
  7699. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7700. outline = self.defaults['global_sel_line']
  7701. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  7702. if self.is_legacy is True:
  7703. self.hover_shapes.redraw()
  7704. def delete_selection_shape(self):
  7705. self.move_tool.sel_shapes.clear()
  7706. self.move_tool.sel_shapes.redraw()
  7707. def draw_selection_shape(self, sel_obj, color=None):
  7708. """
  7709. :param sel_obj: the object for which the selection shape must be drawn
  7710. :return:
  7711. """
  7712. if sel_obj is None:
  7713. return
  7714. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7715. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7716. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7717. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7718. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7719. if self.defaults['units'].upper() == 'MM':
  7720. sel_rect = sel_rect.buffer(-0.1)
  7721. sel_rect = sel_rect.buffer(0.2)
  7722. else:
  7723. sel_rect = sel_rect.buffer(-0.00393)
  7724. sel_rect = sel_rect.buffer(0.00787)
  7725. if color:
  7726. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7727. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7728. else:
  7729. if self.is_legacy is False:
  7730. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7731. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7732. else:
  7733. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  7734. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  7735. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7736. color=outline,
  7737. face_color=face,
  7738. update=True,
  7739. layer=0,
  7740. tolerance=None))
  7741. if self.is_legacy is True:
  7742. self.move_tool.sel_shapes.redraw()
  7743. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7744. """
  7745. :param old_coords: old coordinates
  7746. :param coords: new coordinates
  7747. :return:
  7748. """
  7749. if 'color' in kwargs:
  7750. color = kwargs['color']
  7751. else:
  7752. color = self.defaults['global_sel_line']
  7753. if 'face_color' in kwargs:
  7754. face_color = kwargs['face_color']
  7755. else:
  7756. face_color = self.defaults['global_sel_fill']
  7757. if 'face_alpha' in kwargs:
  7758. face_alpha = kwargs['face_alpha']
  7759. else:
  7760. face_alpha = 0.3
  7761. x0, y0 = old_coords
  7762. x1, y1 = coords
  7763. pt1 = (x0, y0)
  7764. pt2 = (x1, y0)
  7765. pt3 = (x1, y1)
  7766. pt4 = (x0, y1)
  7767. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7768. # color_t = Color(face_color)
  7769. # color_t.alpha = face_alpha
  7770. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7771. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7772. layer=0, tolerance=None)
  7773. if self.is_legacy is True:
  7774. self.move_tool.sel_shapes.redraw()
  7775. def on_file_new_click(self):
  7776. if self.collection.get_list() and self.should_we_save:
  7777. msgbox = QtWidgets.QMessageBox()
  7778. # msgbox.setText("<B>Save changes ...</B>")
  7779. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7780. "Creating a New project will delete them.\n"
  7781. "Do you want to Save the project?"))
  7782. msgbox.setWindowTitle(_("Save changes"))
  7783. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  7784. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7785. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7786. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7787. msgbox.setDefaultButton(bt_yes)
  7788. msgbox.exec_()
  7789. response = msgbox.clickedButton()
  7790. if response == bt_yes:
  7791. self.on_file_saveprojectas()
  7792. elif response == bt_cancel:
  7793. return
  7794. elif response == bt_no:
  7795. self.on_file_new()
  7796. else:
  7797. self.on_file_new()
  7798. self.inform.emit('[success] %s...' % _("New Project created"))
  7799. def on_file_new(self, cli=None):
  7800. """
  7801. Callback for menu item File -> New. Returns the application to its
  7802. startup state. This method is thread-safe.
  7803. :return: None
  7804. """
  7805. self.report_usage("on_file_new")
  7806. # Remove everything from memory
  7807. App.log.debug("on_file_new()")
  7808. if self.call_source != 'app':
  7809. self.editor2object(cleanup=True)
  7810. # ## EDITOR section
  7811. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7812. self.exc_editor = FlatCAMExcEditor(self)
  7813. self.grb_editor = FlatCAMGrbEditor(self)
  7814. # Clear pool
  7815. self.clear_pool()
  7816. for obj in self.collection.get_list():
  7817. # delete shapes left drawn from mark shape_collections, if any
  7818. if isinstance(obj, FlatCAMGerber):
  7819. try:
  7820. for el in obj.mark_shapes:
  7821. obj.mark_shapes[el].clear(update=True)
  7822. obj.mark_shapes[el].enabled = False
  7823. del el
  7824. except AttributeError:
  7825. pass
  7826. # also delete annotation shapes, if any
  7827. elif isinstance(obj, FlatCAMCNCjob):
  7828. try:
  7829. obj.text_col.enabled = False
  7830. del obj.text_col
  7831. obj.annotation.clear(update=True)
  7832. del obj.annotation
  7833. except AttributeError:
  7834. pass
  7835. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7836. self.init_tcl()
  7837. self.delete_selection_shape()
  7838. self.collection.delete_all()
  7839. self.setup_component_editor()
  7840. # Clear project filename
  7841. self.project_filename = None
  7842. # Load the application defaults
  7843. self.load_defaults(filename='current_defaults')
  7844. # Re-fresh project options
  7845. self.on_options_app2project()
  7846. # Init Tools
  7847. self.init_tools()
  7848. if cli is None:
  7849. # Close any Tabs opened in the Plot Tab Area section
  7850. for index in range(self.ui.plot_tab_area.count()):
  7851. self.ui.plot_tab_area.closeTab(index)
  7852. # for whatever reason previous command does not close the last tab so I do it manually
  7853. self.ui.plot_tab_area.closeTab(0)
  7854. # # And then add again the Plot Area
  7855. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7856. self.ui.plot_tab_area.protectTab(0)
  7857. # take the focus of the Notebook on Project Tab.
  7858. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7859. self.set_ui_title(name=_("New Project - Not saved"))
  7860. def obj_properties(self):
  7861. """
  7862. Will launch the object Properties Tool
  7863. :return:
  7864. """
  7865. self.report_usage("obj_properties()")
  7866. self.properties_tool.run(toggle=False)
  7867. def on_project_context_save(self):
  7868. """
  7869. Wrapper, will save the object function of it's type
  7870. :return:
  7871. """
  7872. obj = self.collection.get_active()
  7873. if type(obj) == FlatCAMGeometry:
  7874. self.on_file_exportdxf()
  7875. elif type(obj) == FlatCAMExcellon:
  7876. self.on_file_saveexcellon()
  7877. elif type(obj) == FlatCAMCNCjob:
  7878. obj.on_exportgcode_button_click()
  7879. elif type(obj) == FlatCAMGerber:
  7880. self.on_file_savegerber()
  7881. elif type(obj) == FlatCAMScript:
  7882. self.on_file_savescript()
  7883. elif type(obj) == FlatCAMDocument:
  7884. self.on_file_savedocument()
  7885. def obj_move(self):
  7886. self.report_usage("obj_move()")
  7887. self.move_tool.run(toggle=False)
  7888. def on_fileopengerber(self, signal: bool = None, name=None):
  7889. """
  7890. File menu callback for opening a Gerber.
  7891. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7892. :return: None
  7893. """
  7894. self.report_usage("on_fileopengerber")
  7895. App.log.debug("on_fileopengerber()")
  7896. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7897. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7898. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7899. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7900. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7901. "*.mil);;" \
  7902. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7903. "Allegro Files (*.art);;" \
  7904. "Mentor Files (*.pho *.gdo);;" \
  7905. "All Files (*.*)"
  7906. if name is None:
  7907. try:
  7908. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7909. directory=self.get_last_folder(),
  7910. filter=_filter_)
  7911. except TypeError:
  7912. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7913. filenames = [str(filename) for filename in filenames]
  7914. else:
  7915. filenames = [name]
  7916. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7917. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7918. _("Opening Gerber file.")),
  7919. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7920. color=QtGui.QColor("gray"))
  7921. if len(filenames) == 0:
  7922. self.inform.emit('[WARNING_NOTCL] %s' %
  7923. _("Open Gerber cancelled."))
  7924. else:
  7925. for filename in filenames:
  7926. if filename != '':
  7927. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7928. def on_fileopenexcellon(self, signal: bool = None, name=None):
  7929. """
  7930. File menu callback for opening an Excellon file.
  7931. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7932. :return: None
  7933. """
  7934. self.report_usage("on_fileopenexcellon")
  7935. App.log.debug("on_fileopenexcellon()")
  7936. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7937. "All Files (*.*)"
  7938. if name is None:
  7939. try:
  7940. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7941. directory=self.get_last_folder(),
  7942. filter=_filter_)
  7943. except TypeError:
  7944. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7945. filenames = [str(filename) for filename in filenames]
  7946. else:
  7947. filenames = [str(name)]
  7948. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7949. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7950. _("Opening Excellon file.")),
  7951. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7952. color=QtGui.QColor("gray"))
  7953. if len(filenames) == 0:
  7954. self.inform.emit('[WARNING_NOTCL]%s' %
  7955. _(" Open Excellon cancelled."))
  7956. else:
  7957. for filename in filenames:
  7958. if filename != '':
  7959. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7960. def on_fileopengcode(self, signal: bool = None, name=None):
  7961. """
  7962. File menu call back for opening gcode.
  7963. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7964. :return: None
  7965. """
  7966. self.report_usage("on_fileopengcode")
  7967. App.log.debug("on_fileopengcode()")
  7968. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7969. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7970. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  7971. "All Files (*.*)"
  7972. if name is None:
  7973. try:
  7974. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7975. directory=self.get_last_folder(),
  7976. filter=_filter_)
  7977. except TypeError:
  7978. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7979. filenames = [str(filename) for filename in filenames]
  7980. else:
  7981. filenames = [name]
  7982. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7983. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7984. _("Opening G-Code file.")),
  7985. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7986. color=QtGui.QColor("gray"))
  7987. if len(filenames) == 0:
  7988. self.inform.emit('[WARNING_NOTCL] %s' %
  7989. _("Open G-Code cancelled."))
  7990. else:
  7991. for filename in filenames:
  7992. if filename != '':
  7993. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  7994. def on_file_openproject(self, signal: bool = None):
  7995. """
  7996. File menu callback for opening a project.
  7997. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7998. :return: None
  7999. """
  8000. self.report_usage("on_file_openproject")
  8001. App.log.debug("on_file_openproject()")
  8002. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  8003. try:
  8004. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  8005. directory=self.get_last_folder(), filter=_filter_)
  8006. except TypeError:
  8007. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  8008. # The Qt methods above will return a QString which can cause problems later.
  8009. # So far json.dump() will fail to serialize it.
  8010. # TODO: Improve the serialization methods and remove this fix.
  8011. filename = str(filename)
  8012. if filename == "":
  8013. self.inform.emit('[WARNING_NOTCL] %s' %
  8014. _("Open Project cancelled."))
  8015. else:
  8016. # self.worker_task.emit({'fcn': self.open_project,
  8017. # 'params': [filename]})
  8018. # The above was failing because open_project() is not
  8019. # thread safe. The new_project()
  8020. self.open_project(filename)
  8021. def on_fileopenhpgl2(self, signal: bool = None, name=None):
  8022. """
  8023. File menu callback for opening a HPGL2.
  8024. :param signal: required because clicking the entry will generate a checked signal which needs a container
  8025. :return: None
  8026. """
  8027. self.report_usage("on_fileopenhpgl2")
  8028. App.log.debug("on_fileopenhpgl2()")
  8029. _filter_ = "HPGL2 Files (*.plt);;" \
  8030. "All Files (*.*)"
  8031. if name is None:
  8032. try:
  8033. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  8034. directory=self.get_last_folder(),
  8035. filter=_filter_)
  8036. except TypeError:
  8037. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  8038. filenames = [str(filename) for filename in filenames]
  8039. else:
  8040. filenames = [name]
  8041. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8042. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8043. _("Opening HPGL2 file.")),
  8044. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8045. color=QtGui.QColor("gray"))
  8046. if len(filenames) == 0:
  8047. self.inform.emit('[WARNING_NOTCL] %s' % _("Open HPGL2 file cancelled."))
  8048. else:
  8049. for filename in filenames:
  8050. if filename != '':
  8051. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  8052. def on_file_openconfig(self, signal: bool = None):
  8053. """
  8054. File menu callback for opening a config file.
  8055. :param signal: required because clicking the entry will generate a checked signal which needs a container
  8056. :return: None
  8057. """
  8058. self.report_usage("on_file_openconfig")
  8059. App.log.debug("on_file_openconfig()")
  8060. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  8061. try:
  8062. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  8063. directory=self.data_path, filter=_filter_)
  8064. except TypeError:
  8065. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  8066. filter=_filter_)
  8067. if filename == "":
  8068. self.inform.emit('[WARNING_NOTCL] %s' %
  8069. _("Open Config cancelled."))
  8070. else:
  8071. self.open_config_file(filename)
  8072. def on_file_exportsvg(self):
  8073. """
  8074. Callback for menu item File->Export SVG.
  8075. :return: None
  8076. """
  8077. self.report_usage("on_file_exportsvg")
  8078. App.log.debug("on_file_exportsvg()")
  8079. obj = self.collection.get_active()
  8080. if obj is None:
  8081. self.inform.emit('[WARNING_NOTCL] %s' %
  8082. _("No object selected."))
  8083. msg = _("Please Select a Geometry object to export")
  8084. msgbox = QtWidgets.QMessageBox()
  8085. msgbox.setInformativeText(msg)
  8086. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8087. msgbox.setDefaultButton(bt_ok)
  8088. msgbox.exec_()
  8089. return
  8090. # Check for more compatible types and add as required
  8091. if (not isinstance(obj, FlatCAMGeometry)
  8092. and not isinstance(obj, FlatCAMGerber)
  8093. and not isinstance(obj, FlatCAMCNCjob)
  8094. and not isinstance(obj, FlatCAMExcellon)):
  8095. msg = '[ERROR_NOTCL] %s' % \
  8096. _("Only Geometry, Gerber and CNCJob objects can be used.")
  8097. msgbox = QtWidgets.QMessageBox()
  8098. msgbox.setInformativeText(msg)
  8099. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8100. msgbox.setDefaultButton(bt_ok)
  8101. msgbox.exec_()
  8102. return
  8103. name = obj.options["name"]
  8104. _filter = "SVG File (*.svg);;All Files (*.*)"
  8105. try:
  8106. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8107. caption=_("Export SVG"),
  8108. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  8109. filter=_filter)
  8110. except TypeError:
  8111. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  8112. filename = str(filename)
  8113. if filename == "":
  8114. self.inform.emit('[WARNING_NOTCL]%s' %
  8115. _(" Export SVG cancelled."))
  8116. return
  8117. else:
  8118. self.export_svg(name, filename)
  8119. if self.defaults["global_open_style"] is False:
  8120. self.file_opened.emit("SVG", filename)
  8121. self.file_saved.emit("SVG", filename)
  8122. def on_file_exportpng(self):
  8123. self.report_usage("on_file_exportpng")
  8124. App.log.debug("on_file_exportpng()")
  8125. self.date = str(datetime.today()).rpartition('.')[0]
  8126. self.date = ''.join(c for c in self.date if c not in ':-')
  8127. self.date = self.date.replace(' ', '_')
  8128. if self.is_legacy is False:
  8129. image = _screenshot()
  8130. data = np.asarray(image)
  8131. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  8132. self.inform.emit('[[WARNING_NOTCL]] %s' %
  8133. _('Data must be a 3D array with last dimension 3 or 4'))
  8134. return
  8135. filter_ = "PNG File (*.png);;All Files (*.*)"
  8136. try:
  8137. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8138. caption=_("Export PNG Image"),
  8139. directory=self.get_last_save_folder() + '/png_' + self.date,
  8140. filter=filter_)
  8141. except TypeError:
  8142. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  8143. filename = str(filename)
  8144. if filename == "":
  8145. self.inform.emit(_("Export PNG cancelled."))
  8146. return
  8147. else:
  8148. if self.is_legacy is False:
  8149. write_png(filename, data)
  8150. else:
  8151. self.plotcanvas.figure.savefig(filename)
  8152. if self.defaults["global_open_style"] is False:
  8153. self.file_opened.emit("png", filename)
  8154. self.file_saved.emit("png", filename)
  8155. def on_file_savegerber(self):
  8156. """
  8157. Callback for menu item in Project context menu.
  8158. :return: None
  8159. """
  8160. self.report_usage("on_file_savegerber")
  8161. App.log.debug("on_file_savegerber()")
  8162. obj = self.collection.get_active()
  8163. if obj is None:
  8164. self.inform.emit('[WARNING_NOTCL] %s' %
  8165. _("No object selected. Please select an Gerber object to export."))
  8166. return
  8167. # Check for more compatible types and add as required
  8168. if not isinstance(obj, FlatCAMGerber):
  8169. self.inform.emit('[ERROR_NOTCL] %s' %
  8170. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  8171. return
  8172. name = self.collection.get_active().options["name"]
  8173. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  8174. try:
  8175. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8176. caption="Save Gerber source file",
  8177. directory=self.get_last_save_folder() + '/' + name,
  8178. filter=_filter)
  8179. except TypeError:
  8180. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  8181. filename = str(filename)
  8182. if filename == "":
  8183. self.inform.emit('[WARNING_NOTCL] %s' %
  8184. _("Save Gerber source file cancelled."))
  8185. return
  8186. else:
  8187. self.save_source_file(name, filename)
  8188. if self.defaults["global_open_style"] is False:
  8189. self.file_opened.emit("Gerber", filename)
  8190. self.file_saved.emit("Gerber", filename)
  8191. def on_file_savescript(self):
  8192. """
  8193. Callback for menu item in Project context menu.
  8194. :return: None
  8195. """
  8196. self.report_usage("on_file_savescript")
  8197. App.log.debug("on_file_savescript()")
  8198. obj = self.collection.get_active()
  8199. if obj is None:
  8200. self.inform.emit('[WARNING_NOTCL] %s' %
  8201. _("No object selected. Please select an Script object to export."))
  8202. return
  8203. # Check for more compatible types and add as required
  8204. if not isinstance(obj, FlatCAMScript):
  8205. self.inform.emit('[ERROR_NOTCL] %s' %
  8206. _("Failed. Only Script objects can be saved as TCL Script files..."))
  8207. return
  8208. name = self.collection.get_active().options["name"]
  8209. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  8210. try:
  8211. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8212. caption="Save Script source file",
  8213. directory=self.get_last_save_folder() + '/' + name,
  8214. filter=_filter)
  8215. except TypeError:
  8216. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Script source file"), filter=_filter)
  8217. filename = str(filename)
  8218. if filename == "":
  8219. self.inform.emit('[WARNING_NOTCL] %s' %
  8220. _("Save Script source file cancelled."))
  8221. return
  8222. else:
  8223. self.save_source_file(name, filename)
  8224. if self.defaults["global_open_style"] is False:
  8225. self.file_opened.emit("Script", filename)
  8226. self.file_saved.emit("Script", filename)
  8227. def on_file_savedocument(self):
  8228. """
  8229. Callback for menu item in Project context menu.
  8230. :return: None
  8231. """
  8232. self.report_usage("on_file_savedocument")
  8233. App.log.debug("on_file_savedocument()")
  8234. obj = self.collection.get_active()
  8235. if obj is None:
  8236. self.inform.emit('[WARNING_NOTCL] %s' %
  8237. _("No object selected. Please select an Document object to export."))
  8238. return
  8239. # Check for more compatible types and add as required
  8240. if not isinstance(obj, FlatCAMScript):
  8241. self.inform.emit('[ERROR_NOTCL] %s' %
  8242. _("Failed. Only Document objects can be saved as Document files..."))
  8243. return
  8244. name = self.collection.get_active().options["name"]
  8245. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  8246. try:
  8247. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8248. caption="Save Document source file",
  8249. directory=self.get_last_save_folder() + '/' + name,
  8250. filter=_filter)
  8251. except TypeError:
  8252. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Document source file"), filter=_filter)
  8253. filename = str(filename)
  8254. if filename == "":
  8255. self.inform.emit('[WARNING_NOTCL] %s' %
  8256. _("Save Document source file cancelled."))
  8257. return
  8258. else:
  8259. self.save_source_file(name, filename)
  8260. if self.defaults["global_open_style"] is False:
  8261. self.file_opened.emit("Document", filename)
  8262. self.file_saved.emit("Document", filename)
  8263. def on_file_saveexcellon(self):
  8264. """
  8265. Callback for menu item in project context menu.
  8266. :return: None
  8267. """
  8268. self.report_usage("on_file_saveexcellon")
  8269. App.log.debug("on_file_saveexcellon()")
  8270. obj = self.collection.get_active()
  8271. if obj is None:
  8272. self.inform.emit('[WARNING_NOTCL] %s' %
  8273. _("No object selected. Please select an Excellon object to export."))
  8274. return
  8275. # Check for more compatible types and add as required
  8276. if not isinstance(obj, FlatCAMExcellon):
  8277. self.inform.emit('[ERROR_NOTCL] %s' %
  8278. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8279. return
  8280. name = self.collection.get_active().options["name"]
  8281. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  8282. try:
  8283. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8284. caption=_("Save Excellon source file"),
  8285. directory=self.get_last_save_folder() + '/' + name,
  8286. filter=_filter)
  8287. except TypeError:
  8288. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  8289. filename = str(filename)
  8290. if filename == "":
  8291. self.inform.emit('[WARNING_NOTCL] %s' %
  8292. _("Saving Excellon source file cancelled."))
  8293. return
  8294. else:
  8295. self.save_source_file(name, filename)
  8296. if self.defaults["global_open_style"] is False:
  8297. self.file_opened.emit("Excellon", filename)
  8298. self.file_saved.emit("Excellon", filename)
  8299. def on_file_exportexcellon(self):
  8300. """
  8301. Callback for menu item File->Export->Excellon.
  8302. :return: None
  8303. """
  8304. self.report_usage("on_file_exportexcellon")
  8305. App.log.debug("on_file_exportexcellon()")
  8306. obj = self.collection.get_active()
  8307. if obj is None:
  8308. self.inform.emit('[WARNING_NOTCL] %s' %
  8309. _("No object selected. Please Select an Excellon object to export."))
  8310. return
  8311. # Check for more compatible types and add as required
  8312. if not isinstance(obj, FlatCAMExcellon):
  8313. self.inform.emit('[ERROR_NOTCL] %s' %
  8314. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8315. return
  8316. name = self.collection.get_active().options["name"]
  8317. _filter = self.defaults["excellon_save_filters"]
  8318. try:
  8319. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8320. caption=_("Export Excellon"),
  8321. directory=self.get_last_save_folder() + '/' + name,
  8322. filter=_filter)
  8323. except TypeError:
  8324. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  8325. filename = str(filename)
  8326. if filename == "":
  8327. self.inform.emit('[WARNING_NOTCL] %s' %
  8328. _("Export Excellon cancelled."))
  8329. return
  8330. else:
  8331. used_extension = filename.rpartition('.')[2]
  8332. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  8333. self.export_excellon(name, filename)
  8334. if self.defaults["global_open_style"] is False:
  8335. self.file_opened.emit("Excellon", filename)
  8336. self.file_saved.emit("Excellon", filename)
  8337. def on_file_exportgerber(self):
  8338. """
  8339. Callback for menu item File->Export->Gerber.
  8340. :return: None
  8341. """
  8342. self.report_usage("on_file_exportgerber")
  8343. App.log.debug("on_file_exportgerber()")
  8344. obj = self.collection.get_active()
  8345. if obj is None:
  8346. self.inform.emit('[WARNING_NOTCL] %s' %
  8347. _("No object selected. Please Select an Gerber object to export."))
  8348. return
  8349. # Check for more compatible types and add as required
  8350. if not isinstance(obj, FlatCAMGerber):
  8351. self.inform.emit('[ERROR_NOTCL] %s' %
  8352. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  8353. return
  8354. name = self.collection.get_active().options["name"]
  8355. _filter_ = self.defaults['gerber_save_filters']
  8356. try:
  8357. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8358. caption=_("Export Gerber"),
  8359. directory=self.get_last_save_folder() + '/' + name,
  8360. filter=_filter_)
  8361. except TypeError:
  8362. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  8363. filename = str(filename)
  8364. if filename == "":
  8365. self.inform.emit('[WARNING_NOTCL] %s' %
  8366. _("Export Gerber cancelled."))
  8367. return
  8368. else:
  8369. used_extension = filename.rpartition('.')[2]
  8370. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  8371. self.export_gerber(name, filename)
  8372. if self.defaults["global_open_style"] is False:
  8373. self.file_opened.emit("Gerber", filename)
  8374. self.file_saved.emit("Gerber", filename)
  8375. def on_file_exportdxf(self):
  8376. """
  8377. Callback for menu item File->Export DXF.
  8378. :return: None
  8379. """
  8380. self.report_usage("on_file_exportdxf")
  8381. App.log.debug("on_file_exportdxf()")
  8382. obj = self.collection.get_active()
  8383. if obj is None:
  8384. self.inform.emit('[WARNING_NOTCL] %s' %
  8385. _("No object selected."))
  8386. msg = _("Please Select a Geometry object to export")
  8387. msgbox = QtWidgets.QMessageBox()
  8388. msgbox.setInformativeText(msg)
  8389. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8390. msgbox.setDefaultButton(bt_ok)
  8391. msgbox.exec_()
  8392. return
  8393. # Check for more compatible types and add as required
  8394. if not isinstance(obj, FlatCAMGeometry):
  8395. msg = '[ERROR_NOTCL] %s' % \
  8396. _("Only Geometry objects can be used.")
  8397. msgbox = QtWidgets.QMessageBox()
  8398. msgbox.setInformativeText(msg)
  8399. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8400. msgbox.setDefaultButton(bt_ok)
  8401. msgbox.exec_()
  8402. return
  8403. name = self.collection.get_active().options["name"]
  8404. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8405. try:
  8406. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8407. caption=_("Export DXF"),
  8408. directory=self.get_last_save_folder() + '/' + name,
  8409. filter=_filter_)
  8410. except TypeError:
  8411. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  8412. filter=_filter_)
  8413. filename = str(filename)
  8414. if filename == "":
  8415. self.inform.emit('[WARNING_NOTCL] %s' %
  8416. _("Export DXF cancelled."))
  8417. return
  8418. else:
  8419. self.export_dxf(name, filename)
  8420. if self.defaults["global_open_style"] is False:
  8421. self.file_opened.emit("DXF", filename)
  8422. self.file_saved.emit("DXF", filename)
  8423. def on_file_importsvg(self, type_of_obj):
  8424. """
  8425. Callback for menu item File->Import SVG.
  8426. :param type_of_obj: to import the SVG as Geometry or as Gerber
  8427. :type type_of_obj: str
  8428. :return: None
  8429. """
  8430. self.report_usage("on_file_importsvg")
  8431. App.log.debug("on_file_importsvg()")
  8432. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  8433. try:
  8434. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8435. directory=self.get_last_folder(), filter=_filter_)
  8436. except TypeError:
  8437. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8438. filter=_filter_)
  8439. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8440. type_of_obj = "geometry"
  8441. filenames = [str(filename) for filename in filenames]
  8442. if len(filenames) == 0:
  8443. self.inform.emit('[WARNING_NOTCL] %s' %
  8444. _("Open SVG cancelled."))
  8445. else:
  8446. for filename in filenames:
  8447. if filename != '':
  8448. self.worker_task.emit({'fcn': self.import_svg,
  8449. 'params': [filename, type_of_obj]})
  8450. def on_file_importdxf(self, type_of_obj):
  8451. """
  8452. Callback for menu item File->Import DXF.
  8453. :param type_of_obj: to import the DXF as Geometry or as Gerber
  8454. :type type_of_obj: str
  8455. :return: None
  8456. """
  8457. self.report_usage("on_file_importdxf")
  8458. App.log.debug("on_file_importdxf()")
  8459. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8460. try:
  8461. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8462. directory=self.get_last_folder(),
  8463. filter=_filter_)
  8464. except TypeError:
  8465. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8466. filter=_filter_)
  8467. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8468. type_of_obj = "geometry"
  8469. filenames = [str(filename) for filename in filenames]
  8470. if len(filenames) == 0:
  8471. self.inform.emit('[WARNING_NOTCL] %s' %
  8472. _("Open DXF cancelled."))
  8473. else:
  8474. for filename in filenames:
  8475. if filename != '':
  8476. self.worker_task.emit({'fcn': self.import_dxf,
  8477. 'params': [filename, type_of_obj]})
  8478. # ###############################################################################################################
  8479. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  8480. # ###############################################################################################################
  8481. def init_code_editor(self, name):
  8482. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  8483. # add the tab if it was closed
  8484. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  8485. self.text_editor_tab.setObjectName('text_editor_tab')
  8486. # delete the absolute and relative position and messages in the infobar
  8487. self.ui.position_label.setText("")
  8488. self.ui.rel_position_label.setText("")
  8489. # first clear previous text in text editor (if any)
  8490. self.text_editor_tab.code_editor.clear()
  8491. self.text_editor_tab.code_editor.setReadOnly(False)
  8492. self.toggle_codeeditor = True
  8493. self.text_editor_tab.code_editor.completer_enable = False
  8494. self.text_editor_tab.buttonRun.hide()
  8495. # make sure to keep a reference to the code editor
  8496. self.reference_code_editor = self.text_editor_tab.code_editor
  8497. # Switch plot_area to CNCJob tab
  8498. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  8499. def on_view_source(self):
  8500. """
  8501. Called when the user wants to see the source file of the selected object
  8502. :return:
  8503. """
  8504. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  8505. self.proc_container.view.set_busy(_("Loading..."))
  8506. try:
  8507. obj = self.collection.get_active()
  8508. except Exception as e:
  8509. log.debug("App.on_view_source() --> %s" % str(e))
  8510. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8511. return 'fail'
  8512. if obj is None:
  8513. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8514. return 'fail'
  8515. flt = "All Files (*.*)"
  8516. if obj.kind == 'gerber':
  8517. flt = "Gerber Files (*.GBR);;PDF Files (*.PDF);;All Files (*.*)"
  8518. elif obj.kind == 'excellon':
  8519. flt = "Excellon Files (*.DRL);;PDF Files (*.PDF);;All Files (*.*)"
  8520. elif obj.kind == 'cncjob':
  8521. flt = "GCode Files (*.NC);;PDF Files (*.PDF);;All Files (*.*)"
  8522. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  8523. # add the tab if it was closed
  8524. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  8525. self.source_editor_tab.setObjectName('source_editor_tab')
  8526. # delete the absolute and relative position and messages in the infobar
  8527. self.ui.position_label.setText("")
  8528. self.ui.rel_position_label.setText("")
  8529. # first clear previous text in text editor (if any)
  8530. self.source_editor_tab.code_editor.clear()
  8531. self.source_editor_tab.code_editor.setReadOnly(False)
  8532. self.source_editor_tab.code_editor.completer_enable = False
  8533. self.source_editor_tab.buttonRun.hide()
  8534. # Switch plot_area to CNCJob tab
  8535. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  8536. try:
  8537. self.source_editor_tab.buttonOpen.clicked.disconnect()
  8538. except TypeError:
  8539. pass
  8540. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  8541. try:
  8542. self.source_editor_tab.buttonSave.clicked.disconnect()
  8543. except TypeError:
  8544. pass
  8545. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  8546. # then append the text from GCode to the text editor
  8547. if obj.kind == 'cncjob':
  8548. try:
  8549. file = obj.export_gcode(
  8550. preamble=self.defaults["cncjob_prepend"],
  8551. postamble=self.defaults["cncjob_append"],
  8552. to_file=True)
  8553. if file == 'fail':
  8554. return 'fail'
  8555. except AttributeError:
  8556. self.inform.emit('[WARNING_NOTCL] %s' %
  8557. _("There is no selected object for which to see it's source file code."))
  8558. return 'fail'
  8559. else:
  8560. try:
  8561. file = StringIO(obj.source_file)
  8562. except (AttributeError, TypeError):
  8563. self.inform.emit('[WARNING_NOTCL] %s' %
  8564. _("There is no selected object for which to see it's source file code."))
  8565. return 'fail'
  8566. self.source_editor_tab.t_frame.hide()
  8567. try:
  8568. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  8569. # for line in file:
  8570. # QtWidgets.QApplication.processEvents()
  8571. # proc_line = str(line).strip('\n')
  8572. # self.source_editor_tab.code_editor.append(proc_line)
  8573. except Exception as e:
  8574. log.debug('App.on_view_source() -->%s' % str(e))
  8575. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  8576. return
  8577. self.source_editor_tab.handleTextChanged()
  8578. self.source_editor_tab.t_frame.show()
  8579. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  8580. self.proc_container.view.set_idle()
  8581. # self.ui.show()
  8582. def on_toggle_code_editor(self):
  8583. self.report_usage("on_toggle_code_editor()")
  8584. if self.toggle_codeeditor is False:
  8585. self.init_code_editor(name=_("Code Editor"))
  8586. self.text_editor_tab.buttonOpen.clicked.disconnect()
  8587. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  8588. self.text_editor_tab.buttonSave.clicked.disconnect()
  8589. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  8590. else:
  8591. for idx in range(self.ui.plot_tab_area.count()):
  8592. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  8593. self.ui.plot_tab_area.closeTab(idx)
  8594. break
  8595. self.toggle_codeeditor = False
  8596. def on_code_editor_close(self):
  8597. self.toggle_codeeditor = False
  8598. def goto_text_line(self):
  8599. """
  8600. Will scroll a text to the specified text line.
  8601. :return: None
  8602. """
  8603. dia_box = Dialog_box(title=_("Go to Line ..."),
  8604. label=_("Line:"),
  8605. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  8606. initial_text='')
  8607. try:
  8608. line = int(dia_box.location) - 1
  8609. except (ValueError, TypeError):
  8610. line = 0
  8611. if dia_box.ok:
  8612. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  8613. # at the top of the window
  8614. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  8615. # get the document() of the TextEditor
  8616. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  8617. # create a Text Cursor based on the searched line
  8618. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  8619. # set cursor of the code editor with the cursor at the searcehd line
  8620. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  8621. def on_filenewscript(self, silent=False, name=None, text=None):
  8622. """
  8623. Will create a new script file and open it in the Code Editor
  8624. :param silent: if True will not display status messages
  8625. :param name: if specified will be the name of the new script
  8626. :param text: pass a source file to the newly created script to be loaded in it
  8627. :return: None
  8628. """
  8629. if silent is False:
  8630. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  8631. # delete the absolute and relative position and messages in the infobar
  8632. self.ui.position_label.setText("")
  8633. self.ui.rel_position_label.setText("")
  8634. if name is not None:
  8635. self.new_script_object(name=name, text=text)
  8636. else:
  8637. self.new_script_object(text=text)
  8638. # script_text = script_obj.source_file
  8639. #
  8640. # self.proc_container.view.set_busy(_("Loading..."))
  8641. # script_obj.script_editor_tab.t_frame.hide()
  8642. #
  8643. # script_obj.script_editor_tab.t_frame.show()
  8644. # self.proc_container.view.set_idle()
  8645. def on_fileopenscript(self, name=None, silent=False):
  8646. """
  8647. Will open a Tcl script file into the Code Editor
  8648. :param silent: if True will not display status messages
  8649. :param name: name of a Tcl script file to open
  8650. :return:
  8651. """
  8652. self.report_usage("on_fileopenscript")
  8653. App.log.debug("on_fileopenscript()")
  8654. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8655. if name:
  8656. filenames = [name]
  8657. else:
  8658. try:
  8659. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  8660. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  8661. except TypeError:
  8662. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  8663. if len(filenames) == 0:
  8664. if silent is False:
  8665. self.inform.emit('[WARNING_NOTCL] %s' % _("Open TCL script cancelled."))
  8666. else:
  8667. for filename in filenames:
  8668. if filename != '':
  8669. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  8670. def on_filerunscript(self, name=None, silent=False):
  8671. """
  8672. File menu callback for loading and running a TCL script.
  8673. :param silent: if True will not display status messages
  8674. :param name: name of a Tcl script file to be run by FlatCAM
  8675. :return: None
  8676. """
  8677. self.report_usage("on_filerunscript")
  8678. App.log.debug("on_file_runscript()")
  8679. if name:
  8680. filename = name
  8681. if self.cmd_line_headless != 1:
  8682. self.splash.showMessage('%s: %ssec\n%s' %
  8683. (_("Canvas initialization started.\n"
  8684. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8685. _("Executing FlatCAMScript file.")
  8686. ),
  8687. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8688. color=QtGui.QColor("gray"))
  8689. else:
  8690. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8691. try:
  8692. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  8693. directory=self.get_last_folder(), filter=_filter_)
  8694. except TypeError:
  8695. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  8696. # The Qt methods above will return a QString which can cause problems later.
  8697. # So far json.dump() will fail to serialize it.
  8698. # TODO: Improve the serialization methods and remove this fix.
  8699. filename = str(filename)
  8700. if filename == "":
  8701. if silent is False:
  8702. self.inform.emit('[WARNING_NOTCL] %s' % _("Run TCL script cancelled."))
  8703. else:
  8704. if self.cmd_line_headless != 1:
  8705. if self.ui.shell_dock.isHidden():
  8706. self.ui.shell_dock.show()
  8707. try:
  8708. with open(filename, "r") as tcl_script:
  8709. cmd_line_shellfile_content = tcl_script.read()
  8710. if self.cmd_line_headless != 1:
  8711. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  8712. else:
  8713. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  8714. if silent is False:
  8715. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  8716. except Exception as e:
  8717. log.debug("App.on_filerunscript() -> %s" % str(e))
  8718. sys.exit(2)
  8719. def on_file_saveproject(self, silent=False):
  8720. """
  8721. Callback for menu item File->Save Project. Saves the project to
  8722. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  8723. if set to None. The project is saved by calling ``self.save_project()``.
  8724. :param silent: if True will not display status messages
  8725. :return: None
  8726. """
  8727. self.report_usage("on_file_saveproject")
  8728. if self.project_filename is None:
  8729. self.on_file_saveprojectas()
  8730. else:
  8731. self.worker_task.emit({'fcn': self.save_project,
  8732. 'params': [self.project_filename, silent]})
  8733. if self.defaults["global_open_style"] is False:
  8734. self.file_opened.emit("project", self.project_filename)
  8735. self.file_saved.emit("project", self.project_filename)
  8736. self.set_ui_title(name=self.project_filename)
  8737. self.should_we_save = False
  8738. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  8739. """
  8740. Callback for menu item File->Save Project As... Opens a file
  8741. chooser and saves the project to the given file via
  8742. ``self.save_project()``.
  8743. :param make_copy if to be create a copy of the project; boolean
  8744. :param use_thread: if to be run in a separate thread; boolean
  8745. :param quit_action: if to be followed by quiting the application; boolean
  8746. :return: None
  8747. """
  8748. self.report_usage("on_file_saveprojectas")
  8749. self.date = str(datetime.today()).rpartition('.')[0]
  8750. self.date = ''.join(c for c in self.date if c not in ':-')
  8751. self.date = self.date.replace(' ', '_')
  8752. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  8753. try:
  8754. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8755. caption=_("Save Project As ..."),
  8756. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  8757. proj=_("Project")),
  8758. filter=filter_
  8759. )
  8760. except TypeError:
  8761. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  8762. filename = str(filename)
  8763. if filename == '':
  8764. self.inform.emit('[WARNING_NOTCL] %s' % _("Save Project cancelled."))
  8765. return
  8766. if use_thread is True:
  8767. self.worker_task.emit({'fcn': self.save_project,
  8768. 'params': [filename, quit_action]})
  8769. else:
  8770. self.save_project(filename, quit_action)
  8771. # self.save_project(filename)
  8772. if self.defaults["global_open_style"] is False:
  8773. self.file_opened.emit("project", filename)
  8774. self.file_saved.emit("project", filename)
  8775. if not make_copy:
  8776. self.project_filename = filename
  8777. self.set_ui_title(name=self.project_filename)
  8778. self.should_we_save = False
  8779. def on_file_save_objects_pdf(self, use_thread=True):
  8780. self.date = str(datetime.today()).rpartition('.')[0]
  8781. self.date = ''.join(c for c in self.date if c not in ':-')
  8782. self.date = self.date.replace(' ', '_')
  8783. try:
  8784. obj_selection = self.collection.get_selected()
  8785. if len(obj_selection) == 1:
  8786. obj_name = str(obj_selection[0].options['name'])
  8787. else:
  8788. obj_name = _("FlatCAM objects print")
  8789. except AttributeError as err:
  8790. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  8791. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  8792. return
  8793. if not obj_selection:
  8794. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  8795. return
  8796. filter_ = "PDF File (*.PDF);; All Files (*.*)"
  8797. try:
  8798. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8799. caption=_("Save Object as PDF ..."),
  8800. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  8801. obj_name=obj_name,
  8802. date=self.date),
  8803. filter=filter_
  8804. )
  8805. except TypeError:
  8806. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Object as PDF ..."), filter=filter_)
  8807. filename = str(filename)
  8808. if filename == '':
  8809. self.inform.emit('[WARNING_NOTCL] %s' % _("Save Object PDF cancelled."))
  8810. return
  8811. if use_thread is True:
  8812. proc = self.proc_container.new(_("Printing PDF ... Please wait."))
  8813. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  8814. else:
  8815. self.save_pdf(filename, obj_selection)
  8816. # self.save_project(filename)
  8817. if self.defaults["global_open_style"] is False:
  8818. self.file_opened.emit("pdf", filename)
  8819. self.file_saved.emit("pdf", filename)
  8820. def save_pdf(self, file_name, obj_selection):
  8821. p_size = self.defaults['global_workspaceT']
  8822. orientation = self.defaults['global_workspace_orientation']
  8823. color = 'black'
  8824. transparency_level = 1.0
  8825. self.pagesize = dict()
  8826. self.pagesize.update(
  8827. {
  8828. 'Bounds': None,
  8829. 'A0': (841*mm, 1189*mm),
  8830. 'A1': (594*mm, 841*mm),
  8831. 'A2': (420*mm, 594*mm),
  8832. 'A3': (297*mm, 420*mm),
  8833. 'A4': (210*mm, 297*mm),
  8834. 'A5': (148*mm, 210*mm),
  8835. 'A6': (105*mm, 148*mm),
  8836. 'A7': (74*mm, 105*mm),
  8837. 'A8': (52*mm, 74*mm),
  8838. 'A9': (37*mm, 52*mm),
  8839. 'A10': (26*mm, 37*mm),
  8840. 'B0': (1000*mm, 1414*mm),
  8841. 'B1': (707*mm, 1000*mm),
  8842. 'B2': (500*mm, 707*mm),
  8843. 'B3': (353*mm, 500*mm),
  8844. 'B4': (250*mm, 353*mm),
  8845. 'B5': (176*mm, 250*mm),
  8846. 'B6': (125*mm, 176*mm),
  8847. 'B7': (88*mm, 125*mm),
  8848. 'B8': (62*mm, 88*mm),
  8849. 'B9': (44*mm, 62*mm),
  8850. 'B10': (31*mm, 44*mm),
  8851. 'C0': (917*mm, 1297*mm),
  8852. 'C1': (648*mm, 917*mm),
  8853. 'C2': (458*mm, 648*mm),
  8854. 'C3': (324*mm, 458*mm),
  8855. 'C4': (229*mm, 324*mm),
  8856. 'C5': (162*mm, 229*mm),
  8857. 'C6': (114*mm, 162*mm),
  8858. 'C7': (81*mm, 114*mm),
  8859. 'C8': (57*mm, 81*mm),
  8860. 'C9': (40*mm, 57*mm),
  8861. 'C10': (28*mm, 40*mm),
  8862. # American paper sizes
  8863. 'LETTER': (8.5*inch, 11*inch),
  8864. 'LEGAL': (8.5*inch, 14*inch),
  8865. 'ELEVENSEVENTEEN': (11*inch, 17*inch),
  8866. # From https://en.wikipedia.org/wiki/Paper_size
  8867. 'JUNIOR_LEGAL': (5*inch, 8*inch),
  8868. 'HALF_LETTER': (5.5*inch, 8*inch),
  8869. 'GOV_LETTER': (8*inch, 10.5*inch),
  8870. 'GOV_LEGAL': (8.5*inch, 13*inch),
  8871. 'LEDGER': (17*inch, 11*inch),
  8872. }
  8873. )
  8874. exported_svg = list()
  8875. for obj in obj_selection:
  8876. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  8877. scale_factor_x=None, scale_factor_y=None,
  8878. skew_factor_x=None, skew_factor_y=None,
  8879. mirror=None)
  8880. if obj.kind.lower() == 'gerber':
  8881. # color = self.defaults["gerber_plot_fill"][:-2]
  8882. color = obj.fill_color[:-2]
  8883. elif obj.kind.lower() == 'excellon':
  8884. color = '#C40000'
  8885. elif obj.kind.lower() == 'geometry':
  8886. color = self.defaults["global_draw_color"]
  8887. # Change the attributes of the exported SVG
  8888. # We don't need stroke-width
  8889. # We set opacity to maximum
  8890. # We set the colour to WHITE
  8891. root = ET.fromstring(svg_obj)
  8892. for child in root:
  8893. child.set('fill', str(color))
  8894. child.set('opacity', str(transparency_level))
  8895. child.set('stroke', str(color))
  8896. exported_svg.append(ET.tostring(root))
  8897. xmin = Inf
  8898. ymin = Inf
  8899. xmax = -Inf
  8900. ymax = -Inf
  8901. for obj in obj_selection:
  8902. try:
  8903. gxmin, gymin, gxmax, gymax = obj.bounds()
  8904. xmin = min([xmin, gxmin])
  8905. ymin = min([ymin, gymin])
  8906. xmax = max([xmax, gxmax])
  8907. ymax = max([ymax, gymax])
  8908. except Exception as e:
  8909. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  8910. # Determine bounding area for svg export
  8911. bounds = [xmin, ymin, xmax, ymax]
  8912. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  8913. # This contain the measure units
  8914. uom = obj_selection[0].units.lower()
  8915. # Define a boundary around SVG of about 1.0mm (~39mils)
  8916. if uom in "mm":
  8917. boundary = 1.0
  8918. else:
  8919. boundary = 0.0393701
  8920. # Convert everything to strings for use in the xml doc
  8921. svgwidth = str(size[0] + (2 * boundary))
  8922. svgheight = str(size[1] + (2 * boundary))
  8923. minx = str(bounds[0] - boundary)
  8924. miny = str(bounds[1] + boundary + size[1])
  8925. # Add a SVG Header and footer to the svg output from shapely
  8926. # The transform flips the Y Axis so that everything renders
  8927. # properly within svg apps such as inkscape
  8928. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8929. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8930. svg_header += 'width="' + svgwidth + uom + '" '
  8931. svg_header += 'height="' + svgheight + uom + '" '
  8932. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8933. svg_header += '>'
  8934. svg_header += '<g transform="scale(1,-1)">'
  8935. svg_footer = '</g> </svg>'
  8936. svg_elem = str(svg_header)
  8937. for svg_item in exported_svg:
  8938. svg_elem += str(svg_item)
  8939. svg_elem += str(svg_footer)
  8940. # Parse the xml through a xml parser just to add line feeds
  8941. # and to make it look more pretty for the output
  8942. doc = parse_xml_string(svg_elem)
  8943. doc_final = doc.toprettyxml()
  8944. try:
  8945. if self.defaults['units'].upper() == 'IN':
  8946. unit = inch
  8947. else:
  8948. unit = mm
  8949. doc_final = StringIO(doc_final)
  8950. drawing = svg2rlg(doc_final)
  8951. if p_size == 'Bounds':
  8952. renderPDF.drawToFile(drawing, file_name)
  8953. else:
  8954. if orientation == 'p':
  8955. page_size = portrait(self.pagesize[p_size])
  8956. else:
  8957. page_size = landscape(self.pagesize[p_size])
  8958. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  8959. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  8960. renderPDF.draw(drawing, my_canvas, 0, 0)
  8961. my_canvas.save()
  8962. except Exception as e:
  8963. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  8964. return 'fail'
  8965. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  8966. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  8967. """
  8968. Exports a Geometry Object to an SVG file.
  8969. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8970. :param filename: Path to the SVG file to save to.
  8971. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8972. :return:
  8973. """
  8974. self.report_usage("export_svg()")
  8975. if filename is None:
  8976. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8977. is not None else self.defaults["global_last_folder"]
  8978. self.log.debug("export_svg()")
  8979. try:
  8980. obj = self.collection.get_by_name(str(obj_name))
  8981. except Exception:
  8982. # TODO: The return behavior has not been established... should raise exception?
  8983. return "Could not retrieve object: %s" % obj_name
  8984. with self.proc_container.new(_("Exporting SVG")) as proc:
  8985. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  8986. # Determine bounding area for svg export
  8987. bounds = obj.bounds()
  8988. size = obj.size()
  8989. # Convert everything to strings for use in the xml doc
  8990. svgwidth = str(size[0])
  8991. svgheight = str(size[1])
  8992. minx = str(bounds[0])
  8993. miny = str(bounds[1] - size[1])
  8994. uom = obj.units.lower()
  8995. # Add a SVG Header and footer to the svg output from shapely
  8996. # The transform flips the Y Axis so that everything renders
  8997. # properly within svg apps such as inkscape
  8998. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8999. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  9000. svg_header += 'width="' + svgwidth + uom + '" '
  9001. svg_header += 'height="' + svgheight + uom + '" '
  9002. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  9003. svg_header += '<g transform="scale(1,-1)">'
  9004. svg_footer = '</g> </svg>'
  9005. svg_elem = svg_header + exported_svg + svg_footer
  9006. # Parse the xml through a xml parser just to add line feeds
  9007. # and to make it look more pretty for the output
  9008. svgcode = parse_xml_string(svg_elem)
  9009. svgcode = svgcode.toprettyxml()
  9010. try:
  9011. with open(filename, 'w') as fp:
  9012. fp.write(svgcode)
  9013. except PermissionError:
  9014. self.inform.emit('[WARNING] %s' %
  9015. _("Permission denied, saving not possible.\n"
  9016. "Most likely another app is holding the file open and not accessible."))
  9017. return 'fail'
  9018. if self.defaults["global_open_style"] is False:
  9019. self.file_opened.emit("SVG", filename)
  9020. self.file_saved.emit("SVG", filename)
  9021. self.inform.emit('[success] %s: %s' %
  9022. (_("SVG file exported to"), filename))
  9023. def save_source_file(self, obj_name, filename, use_thread=True):
  9024. """
  9025. Exports a FlatCAM Object to an Gerber/Excellon file.
  9026. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  9027. :param filename: Path to the Gerber file to save to.
  9028. :param use_thread: if to be run in a separate thread
  9029. :return:
  9030. """
  9031. self.report_usage("save source file()")
  9032. if filename is None:
  9033. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  9034. is not None else self.defaults["global_last_folder"]
  9035. self.log.debug("save source file()")
  9036. obj = self.collection.get_by_name(obj_name)
  9037. file_string = StringIO(obj.source_file)
  9038. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  9039. if file_string.getvalue() == '':
  9040. self.inform.emit('[ERROR_NOTCL] %s' %
  9041. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  9042. return 'fail'
  9043. try:
  9044. with open(filename, 'w') as file:
  9045. file.writelines('G04*\n')
  9046. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  9047. (obj.kind.upper(), str(self.version), str(self.version_date)))
  9048. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  9049. file.writelines('G04 Created on : %s*\n' % time_string)
  9050. for line in file_string:
  9051. file.writelines(line)
  9052. except PermissionError:
  9053. self.inform.emit('[WARNING] %s' %
  9054. _("Permission denied, saving not possible.\n"
  9055. "Most likely another app is holding the file open and not accessible."))
  9056. return 'fail'
  9057. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  9058. """
  9059. Exports a Excellon Object to an Excellon file.
  9060. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  9061. :param filename: Path to the Excellon file to save to.
  9062. :param local_use:
  9063. :param use_thread: if to be run in a separate thread
  9064. :return:
  9065. """
  9066. self.report_usage("export_excellon()")
  9067. if filename is None:
  9068. if self.defaults["global_last_save_folder"]:
  9069. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  9070. else:
  9071. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  9072. self.log.debug("export_excellon()")
  9073. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  9074. self.defaults["excellon_exp_decimals"]
  9075. )
  9076. if local_use is None:
  9077. try:
  9078. obj = self.collection.get_by_name(str(obj_name))
  9079. except Exception:
  9080. # TODO: The return behavior has not been established... should raise exception?
  9081. return "Could not retrieve object: %s" % obj_name
  9082. else:
  9083. obj = local_use
  9084. if not isinstance(obj, FlatCAMExcellon):
  9085. self.inform.emit('[ERROR_NOTCL] %s' %
  9086. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  9087. return
  9088. # updated units
  9089. eunits = self.defaults["excellon_exp_units"]
  9090. ewhole = self.defaults["excellon_exp_integer"]
  9091. efract = self.defaults["excellon_exp_decimals"]
  9092. ezeros = self.defaults["excellon_exp_zeros"]
  9093. eformat = self.defaults["excellon_exp_format"]
  9094. slot_type = self.defaults["excellon_exp_slot_type"]
  9095. fc_units = self.defaults['units'].upper()
  9096. if fc_units == 'MM':
  9097. factor = 1 if eunits == 'METRIC' else 0.03937
  9098. else:
  9099. factor = 25.4 if eunits == 'METRIC' else 1
  9100. def make_excellon():
  9101. try:
  9102. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  9103. header = 'M48\n'
  9104. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  9105. (str(self.version), str(self.version_date))
  9106. header += ';Filename: %s' % str(obj_name) + '\n'
  9107. header += ';Created on : %s' % time_str + '\n'
  9108. if eformat == 'dec':
  9109. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  9110. header += eunits + '\n'
  9111. for tool in obj.tools:
  9112. if eunits == 'METRIC':
  9113. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9114. tool=str(tool),
  9115. dec=2)
  9116. else:
  9117. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9118. tool=str(tool),
  9119. dec=4)
  9120. else:
  9121. if ezeros == 'LZ':
  9122. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  9123. form='ndec', e_zeros='LZ', factor=factor,
  9124. slot_type=slot_type)
  9125. header += '%s,%s\n' % (eunits, 'LZ')
  9126. header += format_exc
  9127. for tool in obj.tools:
  9128. if eunits == 'METRIC':
  9129. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9130. tool=str(tool),
  9131. dec=2)
  9132. else:
  9133. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9134. tool=str(tool),
  9135. dec=4)
  9136. else:
  9137. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  9138. form='ndec', e_zeros='TZ', factor=factor,
  9139. slot_type=slot_type)
  9140. header += '%s,%s\n' % (eunits, 'TZ')
  9141. header += format_exc
  9142. for tool in obj.tools:
  9143. if eunits == 'METRIC':
  9144. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9145. tool=str(tool),
  9146. dec=2)
  9147. else:
  9148. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9149. tool=str(tool),
  9150. dec=4)
  9151. header += '%\n'
  9152. footer = 'M30\n'
  9153. exported_excellon = header
  9154. exported_excellon += excellon_code
  9155. exported_excellon += footer
  9156. if local_use is None:
  9157. try:
  9158. with open(filename, 'w') as fp:
  9159. fp.write(exported_excellon)
  9160. except PermissionError:
  9161. self.inform.emit('[WARNING] %s' %
  9162. _("Permission denied, saving not possible.\n"
  9163. "Most likely another app is holding the file open and not accessible."))
  9164. return 'fail'
  9165. if self.defaults["global_open_style"] is False:
  9166. self.file_opened.emit("Excellon", filename)
  9167. self.file_saved.emit("Excellon", filename)
  9168. self.inform.emit('[success] %s: %s' %
  9169. (_("Excellon file exported to"), filename))
  9170. else:
  9171. return exported_excellon
  9172. except Exception as e:
  9173. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  9174. return 'fail'
  9175. if use_thread is True:
  9176. with self.proc_container.new(_("Exporting Excellon")) as proc:
  9177. def job_thread_exc(app_obj):
  9178. ret = make_excellon()
  9179. if ret == 'fail':
  9180. self.inform.emit('[ERROR_NOTCL] %s' %
  9181. _('Could not export Excellon file.'))
  9182. return
  9183. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  9184. else:
  9185. ret = make_excellon()
  9186. if ret == 'fail':
  9187. self.inform.emit('[ERROR_NOTCL] %s' %
  9188. _('Could not export Excellon file.'))
  9189. return 'fail'
  9190. if local_use is not None:
  9191. return ret
  9192. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  9193. """
  9194. Exports a Gerber Object to an Gerber file.
  9195. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  9196. :param filename: Path to the Gerber file to save to.
  9197. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  9198. When not None, the value will be the actual Gerber object for which to create the Gerber code
  9199. :param use_thread: if to be run in a separate thread
  9200. :return:
  9201. """
  9202. self.report_usage("export_gerber()")
  9203. if filename is None:
  9204. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  9205. is not None else self.defaults["global_last_folder"]
  9206. self.log.debug("export_gerber()")
  9207. if local_use is None:
  9208. try:
  9209. obj = self.collection.get_by_name(str(obj_name))
  9210. except Exception:
  9211. # TODO: The return behavior has not been established... should raise exception?
  9212. return "Could not retrieve object: %s" % obj_name
  9213. else:
  9214. obj = local_use
  9215. # updated units
  9216. gunits = self.defaults["gerber_exp_units"]
  9217. gwhole = self.defaults["gerber_exp_integer"]
  9218. gfract = self.defaults["gerber_exp_decimals"]
  9219. gzeros = self.defaults["gerber_exp_zeros"]
  9220. fc_units = self.defaults['units'].upper()
  9221. if fc_units == 'MM':
  9222. factor = 1 if gunits == 'MM' else 0.03937
  9223. else:
  9224. factor = 25.4 if gunits == 'MM' else 1
  9225. def make_gerber():
  9226. try:
  9227. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  9228. header = 'G04*\n'
  9229. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  9230. (str(self.version), str(self.version_date))
  9231. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  9232. header += 'G04 Created on : %s*' % time_str + '\n'
  9233. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  9234. header += "%MO{units}*%\n".format(units=gunits)
  9235. for apid in obj.apertures:
  9236. if obj.apertures[apid]['type'] == 'C':
  9237. header += "%ADD{apid}{type},{size}*%\n".format(
  9238. apid=str(apid),
  9239. type='C',
  9240. size=(factor * obj.apertures[apid]['size'])
  9241. )
  9242. elif obj.apertures[apid]['type'] == 'R':
  9243. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  9244. apid=str(apid),
  9245. type='R',
  9246. width=(factor * obj.apertures[apid]['width']),
  9247. height=(factor * obj.apertures[apid]['height'])
  9248. )
  9249. elif obj.apertures[apid]['type'] == 'O':
  9250. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  9251. apid=str(apid),
  9252. type='O',
  9253. width=(factor * obj.apertures[apid]['width']),
  9254. height=(factor * obj.apertures[apid]['height'])
  9255. )
  9256. header += '\n'
  9257. # obsolete units but some software may need it
  9258. if gunits == 'IN':
  9259. header += 'G70*\n'
  9260. else:
  9261. header += 'G71*\n'
  9262. # Absolute Mode
  9263. header += 'G90*\n'
  9264. header += 'G01*\n'
  9265. # positive polarity
  9266. header += '%LPD*%\n'
  9267. footer = 'M02*\n'
  9268. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  9269. exported_gerber = header
  9270. exported_gerber += gerber_code
  9271. exported_gerber += footer
  9272. if local_use is None:
  9273. try:
  9274. with open(filename, 'w') as fp:
  9275. fp.write(exported_gerber)
  9276. except PermissionError:
  9277. self.inform.emit('[WARNING] %s' %
  9278. _("Permission denied, saving not possible.\n"
  9279. "Most likely another app is holding the file open and not accessible."))
  9280. return 'fail'
  9281. if self.defaults["global_open_style"] is False:
  9282. self.file_opened.emit("Gerber", filename)
  9283. self.file_saved.emit("Gerber", filename)
  9284. self.inform.emit('[success] %s: %s' %
  9285. (_("Gerber file exported to"), filename))
  9286. else:
  9287. return exported_gerber
  9288. except Exception as e:
  9289. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  9290. return 'fail'
  9291. if use_thread is True:
  9292. with self.proc_container.new(_("Exporting Gerber")) as proc:
  9293. def job_thread_grb(app_obj):
  9294. ret = make_gerber()
  9295. if ret == 'fail':
  9296. self.inform.emit('[ERROR_NOTCL] %s' %
  9297. _('Could not export Gerber file.'))
  9298. return
  9299. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  9300. else:
  9301. ret = make_gerber()
  9302. if ret == 'fail':
  9303. self.inform.emit('[ERROR_NOTCL] %s' %
  9304. _('Could not export Gerber file.'))
  9305. return 'fail'
  9306. if local_use is not None:
  9307. return ret
  9308. def export_dxf(self, obj_name, filename, use_thread=True):
  9309. """
  9310. Exports a Geometry Object to an DXF file.
  9311. :param obj_name: the name of the FlatCAM object to be saved as DXF
  9312. :param filename: Path to the DXF file to save to.
  9313. :param use_thread: if to be run in a separate thread
  9314. :return:
  9315. """
  9316. self.report_usage("export_dxf()")
  9317. if filename is None:
  9318. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  9319. is not None else self.defaults["global_last_folder"]
  9320. self.log.debug("export_dxf()")
  9321. try:
  9322. obj = self.collection.get_by_name(str(obj_name))
  9323. except Exception:
  9324. # TODO: The return behavior has not been established... should raise exception?
  9325. return "Could not retrieve object: %s" % obj_name
  9326. def make_dxf():
  9327. try:
  9328. dxf_code = obj.export_dxf()
  9329. dxf_code.saveas(filename)
  9330. if self.defaults["global_open_style"] is False:
  9331. self.file_opened.emit("DXF", filename)
  9332. self.file_saved.emit("DXF", filename)
  9333. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  9334. except Exception:
  9335. return 'fail'
  9336. if use_thread is True:
  9337. with self.proc_container.new(_("Exporting DXF")) as proc:
  9338. def job_thread_exc(app_obj):
  9339. ret_dxf_val = make_dxf()
  9340. if ret_dxf_val == 'fail':
  9341. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  9342. return
  9343. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  9344. else:
  9345. ret = make_dxf()
  9346. if ret == 'fail':
  9347. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  9348. return
  9349. def import_svg(self, filename, geo_type='geometry', outname=None):
  9350. """
  9351. Adds a new Geometry Object to the projects and populates
  9352. it with shapes extracted from the SVG file.
  9353. :param filename: Path to the SVG file.
  9354. :param geo_type: Type of FlatCAM object that will be created from SVG
  9355. :param outname:
  9356. :return:
  9357. """
  9358. self.report_usage("import_svg()")
  9359. log.debug("App.import_svg()")
  9360. obj_type = ""
  9361. if geo_type is None or geo_type == "geometry":
  9362. obj_type = "geometry"
  9363. elif geo_type == "gerber":
  9364. obj_type = "gerber"
  9365. else:
  9366. self.inform.emit('[ERROR_NOTCL] %s' %
  9367. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  9368. return
  9369. units = self.defaults['units'].upper()
  9370. def obj_init(geo_obj, app_obj):
  9371. geo_obj.import_svg(filename, obj_type, units=units)
  9372. geo_obj.multigeo = False
  9373. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  9374. with self.proc_container.new(_("Importing SVG")) as proc:
  9375. # Object name
  9376. name = outname or filename.split('/')[-1].split('\\')[-1]
  9377. self.new_object(obj_type, name, obj_init, autoselected=False)
  9378. # Register recent file
  9379. self.file_opened.emit("svg", filename)
  9380. # GUI feedback
  9381. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9382. def import_dxf(self, filename, geo_type='geometry', outname=None):
  9383. """
  9384. Adds a new Geometry Object to the projects and populates
  9385. it with shapes extracted from the DXF file.
  9386. :param filename: Path to the DXF file.
  9387. :param geo_type: Type of FlatCAM object that will be created from DXF
  9388. :param outname:
  9389. :type putname: str
  9390. :return:
  9391. """
  9392. self.report_usage("import_dxf()")
  9393. obj_type = ""
  9394. if geo_type is None or geo_type == "geometry":
  9395. obj_type = "geometry"
  9396. elif geo_type == "gerber":
  9397. obj_type = geo_type
  9398. else:
  9399. self.inform.emit('[ERROR_NOTCL] %s' %
  9400. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  9401. return
  9402. units = self.defaults['units'].upper()
  9403. def obj_init(geo_obj, app_obj):
  9404. geo_obj.import_dxf(filename, obj_type, units=units)
  9405. geo_obj.multigeo = False
  9406. with self.proc_container.new(_("Importing DXF")) as proc:
  9407. # Object name
  9408. name = outname or filename.split('/')[-1].split('\\')[-1]
  9409. self.new_object(obj_type, name, obj_init, autoselected=False)
  9410. # Register recent file
  9411. self.file_opened.emit("dxf", filename)
  9412. # GUI feedback
  9413. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9414. def open_gerber(self, filename, outname=None):
  9415. """
  9416. Opens a Gerber file, parses it and creates a new object for
  9417. it in the program. Thread-safe.
  9418. :param outname: Name of the resulting object. None causes the
  9419. name to be that of the file.
  9420. :param filename: Gerber file filename
  9421. :type filename: str
  9422. :return: None
  9423. """
  9424. # How the object should be initialized
  9425. def obj_init(gerber_obj, app_obj):
  9426. assert isinstance(gerber_obj, FlatCAMGerber), \
  9427. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  9428. # Opening the file happens here
  9429. try:
  9430. gerber_obj.parse_file(filename)
  9431. except IOError:
  9432. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  9433. return "fail"
  9434. except ParseError as err:
  9435. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  9436. app_obj.log.error(str(err))
  9437. return "fail"
  9438. except Exception as e:
  9439. log.debug("App.open_gerber() --> %s" % str(e))
  9440. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  9441. msg += traceback.format_exc()
  9442. app_obj.inform.emit(msg)
  9443. return "fail"
  9444. if gerber_obj.is_empty():
  9445. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  9446. _("Object is not Gerber file or empty. Aborting object creation."))
  9447. return "fail"
  9448. App.log.debug("open_gerber()")
  9449. with self.proc_container.new(_("Opening Gerber")) as proc:
  9450. # Object name
  9451. name = outname or filename.split('/')[-1].split('\\')[-1]
  9452. # # ## Object creation # ##
  9453. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  9454. if ret == 'fail':
  9455. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open Gerber failed. Probable not a Gerber file.'))
  9456. return 'fail'
  9457. # Register recent file
  9458. self.file_opened.emit("gerber", filename)
  9459. # GUI feedback
  9460. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9461. def open_excellon(self, filename, outname=None, plot=True):
  9462. """
  9463. Opens an Excellon file, parses it and creates a new object for
  9464. it in the program. Thread-safe.
  9465. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9466. :param filename: Excellon file filename
  9467. :type filename: str
  9468. :param plot: boolean, to plot or not the resulting object
  9469. :return: None
  9470. """
  9471. App.log.debug("open_excellon()")
  9472. # How the object should be initialized
  9473. def obj_init(excellon_obj, app_obj):
  9474. try:
  9475. ret = excellon_obj.parse_file(filename=filename)
  9476. if ret == "fail":
  9477. log.debug("Excellon parsing failed.")
  9478. self.inform.emit('[ERROR_NOTCL] %s' %
  9479. _("This is not Excellon file."))
  9480. return "fail"
  9481. except IOError:
  9482. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9483. (_("Cannot open file"), filename))
  9484. log.debug("Could not open Excellon object.")
  9485. return "fail"
  9486. except Exception:
  9487. msg = '[ERROR_NOTCL] %s' % \
  9488. _("An internal error has occurred. See shell.\n")
  9489. msg += traceback.format_exc()
  9490. app_obj.inform.emit(msg)
  9491. return "fail"
  9492. ret = excellon_obj.create_geometry()
  9493. if ret == 'fail':
  9494. log.debug("Could not create geometry for Excellon object.")
  9495. return "fail"
  9496. for tool in excellon_obj.tools:
  9497. if excellon_obj.tools[tool]['solid_geometry']:
  9498. return
  9499. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9500. (_("No geometry found in file"), filename))
  9501. return "fail"
  9502. with self.proc_container.new(_("Opening Excellon.")):
  9503. # Object name
  9504. name = outname or filename.split('/')[-1].split('\\')[-1]
  9505. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  9506. if ret_val == 'fail':
  9507. self.inform.emit('[ERROR_NOTCL] %s' %
  9508. _('Open Excellon file failed. Probable not an Excellon file.'))
  9509. return
  9510. # Register recent file
  9511. self.file_opened.emit("excellon", filename)
  9512. # GUI feedback
  9513. self.inform.emit('[success] %s: %s' %
  9514. (_("Opened"), filename))
  9515. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True):
  9516. """
  9517. Opens a G-gcode file, parses it and creates a new object for
  9518. it in the program. Thread-safe.
  9519. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9520. :param filename: G-code file filename
  9521. :type filename: str
  9522. :return: None
  9523. """
  9524. App.log.debug("open_gcode()")
  9525. # How the object should be initialized
  9526. def obj_init(job_obj, app_obj_):
  9527. """
  9528. :param job_obj: the resulting object
  9529. :type app_obj_: App
  9530. """
  9531. assert isinstance(app_obj_, App), \
  9532. "Initializer expected App, got %s" % type(app_obj_)
  9533. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  9534. try:
  9535. f = open(filename)
  9536. gcode = f.read()
  9537. f.close()
  9538. except IOError:
  9539. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  9540. (_("Failed to open"), filename))
  9541. return "fail"
  9542. job_obj.gcode = gcode
  9543. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  9544. if gcode_ret == "fail":
  9545. self.inform.emit('[ERROR_NOTCL] %s' %
  9546. _("This is not GCODE"))
  9547. return "fail"
  9548. job_obj.create_geometry()
  9549. with self.proc_container.new(_("Opening G-Code.")):
  9550. # Object name
  9551. name = outname or filename.split('/')[-1].split('\\')[-1]
  9552. # New object creation and file processing
  9553. obj_ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  9554. if obj_ret == 'fail':
  9555. self.inform.emit('[ERROR_NOTCL] %s' %
  9556. _("Failed to create CNCJob Object. Probable not a GCode file. "
  9557. "Try to load it from File menu.\n "
  9558. "Attempting to create a FlatCAM CNCJob Object from "
  9559. "G-Code file failed during processing"))
  9560. return "fail"
  9561. # Register recent file
  9562. self.file_opened.emit("cncjob", filename)
  9563. # GUI feedback
  9564. self.inform.emit('[success] %s: %s' %
  9565. (_("Opened"), filename))
  9566. def open_hpgl2(self, filename, outname=None):
  9567. """
  9568. Opens a HPGL2 file, parses it and creates a new object for
  9569. it in the program. Thread-safe.
  9570. :param outname: Name of the resulting object. None causes the
  9571. name to be that of the file.
  9572. :param filename: HPGL2 file filename
  9573. :type filename: str
  9574. :return: None
  9575. """
  9576. filename = filename
  9577. # How the object should be initialized
  9578. def obj_init(geo_obj, app_obj):
  9579. assert isinstance(geo_obj, FlatCAMGeometry), \
  9580. "Expected to initialize a FlatCAMGeometry but got %s" % type(geo_obj)
  9581. # Opening the file happens here
  9582. obj = HPGL2(self)
  9583. try:
  9584. HPGL2.parse_file(obj, filename)
  9585. except IOError:
  9586. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  9587. return "fail"
  9588. except ParseError as err:
  9589. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  9590. app_obj.log.error(str(err))
  9591. return "fail"
  9592. except Exception as e:
  9593. log.debug("App.open_hpgl2() --> %s" % str(e))
  9594. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  9595. msg += traceback.format_exc()
  9596. app_obj.inform.emit(msg)
  9597. return "fail"
  9598. geo_obj.multigeo = True
  9599. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  9600. geo_obj.tools = deepcopy(obj.tools)
  9601. geo_obj.source_file = deepcopy(obj.source_file)
  9602. del obj
  9603. if not geo_obj.solid_geometry:
  9604. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  9605. _("Object is not HPGL2 file or empty. Aborting object creation."))
  9606. return "fail"
  9607. App.log.debug("open_hpgl2()")
  9608. with self.proc_container.new(_("Opening HPGL2")) as proc:
  9609. # Object name
  9610. name = outname or filename.split('/')[-1].split('\\')[-1]
  9611. # # ## Object creation # ##
  9612. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  9613. if ret == 'fail':
  9614. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  9615. return 'fail'
  9616. # Register recent file
  9617. self.file_opened.emit("geometry", filename)
  9618. # GUI feedback
  9619. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9620. def open_script(self, filename, outname=None, silent=False):
  9621. """
  9622. Opens a Script file, parses it and creates a new object for
  9623. it in the program. Thread-safe.
  9624. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9625. :param filename: Script file filename
  9626. :type filename: str
  9627. :return: None
  9628. """
  9629. App.log.debug("open_script()")
  9630. with self.proc_container.new(_("Opening TCL Script...")):
  9631. try:
  9632. with open(filename, "r") as opened_script:
  9633. script_content = opened_script.readlines()
  9634. script_content = ''.join(script_content)
  9635. if silent is False:
  9636. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  9637. except Exception as e:
  9638. log.debug("App.open_script() -> %s" % str(e))
  9639. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  9640. return
  9641. # Object name
  9642. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  9643. # New object creation and file processing
  9644. self.on_filenewscript(name=script_name, text=script_content)
  9645. # Register recent file
  9646. self.file_opened.emit("script", filename)
  9647. # GUI feedback
  9648. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9649. def open_config_file(self, filename, run_from_arg=None):
  9650. """
  9651. Loads a config file from the specified file.
  9652. :param filename: Name of the file from which to load.
  9653. :type filename: str
  9654. :return: None
  9655. """
  9656. App.log.debug("Opening config file: " + filename)
  9657. if run_from_arg:
  9658. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9659. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9660. _("Opening FlatCAM Config file.")),
  9661. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9662. color=QtGui.QColor("gray"))
  9663. # # add the tab if it was closed
  9664. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  9665. # # first clear previous text in text editor (if any)
  9666. # self.ui.text_editor_tab.code_editor.clear()
  9667. #
  9668. # # Switch plot_area to CNCJob tab
  9669. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  9670. # close the Code editor if already open
  9671. if self.toggle_codeeditor:
  9672. self.on_toggle_code_editor()
  9673. self.on_toggle_code_editor()
  9674. try:
  9675. if filename:
  9676. f = QtCore.QFile(filename)
  9677. if f.open(QtCore.QIODevice.ReadOnly):
  9678. stream = QtCore.QTextStream(f)
  9679. code_edited = stream.readAll()
  9680. self.text_editor_tab.code_editor.setPlainText(code_edited)
  9681. f.close()
  9682. except IOError:
  9683. App.log.error("Failed to open config file: %s" % filename)
  9684. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9685. (_("Failed to open config file"), filename))
  9686. return
  9687. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  9688. """
  9689. Loads a project from the specified file.
  9690. 1) Loads and parses file
  9691. 2) Registers the file as recently opened.
  9692. 3) Calls on_file_new()
  9693. 4) Updates options
  9694. 5) Calls new_object() with the object's from_dict() as init method.
  9695. 6) Calls plot_all() if plot=True
  9696. :param filename: Name of the file from which to load.
  9697. :type filename: str
  9698. :param run_from_arg: True if run for arguments
  9699. :param plot: If True plot all objects in the project
  9700. :param cli: run from command line
  9701. :return: None
  9702. """
  9703. App.log.debug("Opening project: " + filename)
  9704. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9705. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9706. if cli is None:
  9707. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  9708. if run_from_arg:
  9709. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9710. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9711. _("Opening FlatCAM Project file.")),
  9712. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9713. color=QtGui.QColor("gray"))
  9714. # Open and parse an uncompressed Project file
  9715. try:
  9716. f = open(filename, 'r')
  9717. except IOError:
  9718. App.log.error("Failed to open project file: %s" % filename)
  9719. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9720. (_("Failed to open project file"), filename))
  9721. return
  9722. try:
  9723. d = json.load(f, object_hook=dict2obj)
  9724. except Exception as e:
  9725. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  9726. (filename, str(e)))
  9727. f.close()
  9728. # Open and parse a compressed Project file
  9729. try:
  9730. with lzma.open(filename) as f:
  9731. file_content = f.read().decode('utf-8')
  9732. d = json.loads(file_content, object_hook=dict2obj)
  9733. except Exception as e:
  9734. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  9735. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9736. (_("Failed to open project file"), filename))
  9737. return
  9738. # Clear the current project
  9739. # # NOT THREAD SAFE # ##
  9740. if run_from_arg is True:
  9741. pass
  9742. elif cli is True:
  9743. self.delete_selection_shape()
  9744. else:
  9745. self.on_file_new()
  9746. # Project options
  9747. self.options.update(d['options'])
  9748. self.project_filename = filename
  9749. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9750. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9751. if cli is None:
  9752. self.set_screen_units(self.options["units"])
  9753. # Re create objects
  9754. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  9755. for obj in d['objs']:
  9756. try:
  9757. def obj_init(obj_inst, app_inst):
  9758. obj_inst.from_dict(obj)
  9759. App.log.debug("Recreating from opened project an %s object: %s" %
  9760. (obj['kind'].capitalize(), obj['options']['name']))
  9761. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9762. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9763. if cli is None:
  9764. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  9765. obj['kind'].upper(),
  9766. obj['options']['name']
  9767. )
  9768. )
  9769. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  9770. except Exception as e:
  9771. print('App.open_project() --> ' + str(e))
  9772. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  9773. self.should_we_save = False
  9774. self.file_opened.emit("project", filename)
  9775. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9776. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9777. if cli is None:
  9778. self.set_ui_title(name=self.project_filename)
  9779. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9780. def propagate_defaults(self, silent=False):
  9781. """
  9782. This method is used to set default values in classes. It's
  9783. an alternative to project options but allows the use
  9784. of values invisible to the user.
  9785. :return: None
  9786. """
  9787. if silent is False:
  9788. self.log.debug("propagate_defaults()")
  9789. # Which objects to update the given parameters.
  9790. routes = {
  9791. "global_zdownrate": CNCjob,
  9792. "excellon_zeros": Excellon,
  9793. "excellon_format_upper_in": Excellon,
  9794. "excellon_format_lower_in": Excellon,
  9795. "excellon_format_upper_mm": Excellon,
  9796. "excellon_format_lower_mm": Excellon,
  9797. "excellon_units": Excellon,
  9798. "gerber_use_buffer_for_union": Gerber,
  9799. "geometry_multidepth": Geometry
  9800. }
  9801. for param in routes:
  9802. if param in routes[param].defaults:
  9803. try:
  9804. routes[param].defaults[param] = self.defaults[param]
  9805. if silent is False:
  9806. self.log.debug(" " + param + " OK")
  9807. except KeyError:
  9808. if silent is False:
  9809. self.log.debug("FlatCAMApp.propagate_defaults() --> ERROR: " + param + " not in defaults.")
  9810. else:
  9811. # Try extracting the name:
  9812. # classname_param here is param in the object
  9813. if param.find(routes[param].__name__.lower() + "_") == 0:
  9814. p = param[len(routes[param].__name__) + 1:]
  9815. if p in routes[param].defaults:
  9816. routes[param].defaults[p] = self.defaults[param]
  9817. if silent is False:
  9818. self.log.debug(" " + param + " OK!")
  9819. def plot_all(self, zoom=True):
  9820. """
  9821. Re-generates all plots from all objects.
  9822. :return: None
  9823. """
  9824. self.log.debug("Plot_all()")
  9825. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9826. for obj in self.collection.get_list():
  9827. def worker_task(obj):
  9828. with self.proc_container.new("Plotting"):
  9829. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9830. if zoom:
  9831. self.object_plotted.emit(obj)
  9832. # Send to worker
  9833. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  9834. def register_folder(self, filename):
  9835. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9836. def register_save_folder(self, filename):
  9837. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9838. def set_progress_bar(self, percentage, text=""):
  9839. self.ui.progress_bar.setValue(int(percentage))
  9840. def setup_shell(self):
  9841. """
  9842. Creates shell functions. Runs once at startup.
  9843. :return: None
  9844. """
  9845. self.log.debug("setup_shell()")
  9846. def shelp(p=None):
  9847. if not p:
  9848. return _("Available commands:\n") + \
  9849. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  9850. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  9851. if p not in commands:
  9852. return "Unknown command: %s" % p
  9853. return commands[p]["help"]
  9854. # --- Migrated to new architecture ---
  9855. # def options(name):
  9856. # ops = self.collection.get_by_name(str(name)).options
  9857. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  9858. def h(*args):
  9859. """
  9860. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  9861. and standalone parameters into list.
  9862. """
  9863. kwa = {}
  9864. a = []
  9865. n = len(args)
  9866. name = None
  9867. for i in range(n):
  9868. match = re.search(r'^-([a-zA-Z].*)', args[i])
  9869. if match:
  9870. assert name is None
  9871. name = match.group(1)
  9872. continue
  9873. if name is None:
  9874. a.append(args[i])
  9875. else:
  9876. kwa[name] = args[i]
  9877. name = None
  9878. return a, kwa
  9879. @contextmanager
  9880. def wait_signal(signal, timeout=10000):
  9881. """
  9882. Block loop until signal emitted, timeout (ms) elapses
  9883. or unhandled exception happens in a thread.
  9884. :param timeout: time after which the loop is exited
  9885. :param signal: Signal to wait for.
  9886. """
  9887. loop = QtCore.QEventLoop()
  9888. # Normal termination
  9889. signal.connect(loop.quit)
  9890. # Termination by exception in thread
  9891. self.thread_exception.connect(loop.quit)
  9892. status = {'timed_out': False}
  9893. def report_quit():
  9894. status['timed_out'] = True
  9895. loop.quit()
  9896. yield
  9897. # Temporarily change how exceptions are managed.
  9898. oeh = sys.excepthook
  9899. ex = []
  9900. def except_hook(type_, value, traceback_):
  9901. ex.append(value)
  9902. oeh(type_, value, traceback_)
  9903. sys.excepthook = except_hook
  9904. # Terminate on timeout
  9905. if timeout is not None:
  9906. QtCore.QTimer.singleShot(timeout, report_quit)
  9907. # # ## Block ## ##
  9908. loop.exec_()
  9909. # Restore exception management
  9910. sys.excepthook = oeh
  9911. if ex:
  9912. self.raiseTclError(str(ex[0]))
  9913. if status['timed_out']:
  9914. raise Exception('Timed out!')
  9915. def make_docs():
  9916. output = ''
  9917. import collections
  9918. od = collections.OrderedDict(sorted(commands.items()))
  9919. for cmd_, val in od.items():
  9920. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9921. t = val['help']
  9922. usage_i = t.find('>')
  9923. if usage_i < 0:
  9924. expl = t
  9925. output += expl + '\n\n'
  9926. continue
  9927. expl = t[:usage_i - 1]
  9928. output += expl + '\n\n'
  9929. end_usage_i = t[usage_i:].find('\n')
  9930. if end_usage_i < 0:
  9931. end_usage_i = len(t[usage_i:])
  9932. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9933. else:
  9934. extras = t[usage_i+end_usage_i+1:]
  9935. parts = [s.strip() for s in extras.split('\n')]
  9936. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9937. for p in parts:
  9938. output += ' ' + p + '\n\n'
  9939. return output
  9940. '''
  9941. Howto implement TCL shell commands:
  9942. All parameters passed to command should be possible to set as None and test it afterwards.
  9943. This is because we need to see error caused in tcl,
  9944. if None value as default parameter is not allowed TCL will return empty error.
  9945. Use:
  9946. def mycommand(name=None,...):
  9947. Test it like this:
  9948. if name is None:
  9949. self.raise_tcl_error('Argument name is missing.')
  9950. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9951. otherwise we will miss it and processing will silently continue.
  9952. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9953. which is catched in exec_command and displayed in TCL shell console with red background.
  9954. Error in console is displayed with TCL trace.
  9955. This behavior works only within main thread,
  9956. errors with promissed tasks can be catched and detected only with log.
  9957. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9958. TCL shell.
  9959. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9960. '''
  9961. commands = {
  9962. 'help': {
  9963. 'fcn': shelp,
  9964. 'help': _("Shows list of commands.")
  9965. },
  9966. }
  9967. # Import/overwrite tcl commands as objects of TclCommand descendants
  9968. # This modifies the variable 'commands'.
  9969. tclCommands.register_all_commands(self, commands)
  9970. # Add commands to the tcl interpreter
  9971. for cmd in commands:
  9972. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9973. # Make the tcl puts function return instead of print to stdout
  9974. self.tcl.eval('''
  9975. rename puts original_puts
  9976. proc puts {args} {
  9977. if {[llength $args] == 1} {
  9978. return "[lindex $args 0]"
  9979. } else {
  9980. eval original_puts $args
  9981. }
  9982. }
  9983. ''')
  9984. def setup_recent_items(self):
  9985. # TODO: Move this to constructor
  9986. icons = {
  9987. "gerber": self.resource_location + "/flatcam_icon16.png",
  9988. "excellon": self.resource_location + "/drill16.png",
  9989. 'geometry': self.resource_location + "/geometry16.png",
  9990. "cncjob": self.resource_location + "/cnc16.png",
  9991. "script": self.resource_location + "/script_new24.png",
  9992. "document": self.resource_location + "/notes16_1.png",
  9993. "project": self.resource_location + "/project16.png",
  9994. "svg": self.resource_location + "/geometry16.png",
  9995. "dxf": self.resource_location + "/dxf16.png",
  9996. "pdf": self.resource_location + "/pdf32.png",
  9997. "image": self.resource_location + "/image16.png"
  9998. }
  9999. try:
  10000. image_opener = self.image_tool.import_image
  10001. except AttributeError:
  10002. image_opener = None
  10003. openers = {
  10004. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  10005. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  10006. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  10007. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  10008. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  10009. "document": None,
  10010. 'project': self.open_project,
  10011. 'svg': self.import_svg,
  10012. 'dxf': self.import_dxf,
  10013. 'image': image_opener,
  10014. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  10015. }
  10016. # Open recent file for files
  10017. try:
  10018. f = open(self.data_path + '/recent.json')
  10019. except IOError:
  10020. App.log.error("Failed to load recent item list.")
  10021. self.inform.emit('[ERROR_NOTCL] %s' %
  10022. _("Failed to load recent item list."))
  10023. return
  10024. try:
  10025. self.recent = json.load(f)
  10026. except json.scanner.JSONDecodeError:
  10027. App.log.error("Failed to parse recent item list.")
  10028. self.inform.emit('[ERROR_NOTCL] %s' %
  10029. _("Failed to parse recent item list."))
  10030. f.close()
  10031. return
  10032. f.close()
  10033. # Open recent file for projects
  10034. try:
  10035. fp = open(self.data_path + '/recent_projects.json')
  10036. except IOError:
  10037. App.log.error("Failed to load recent project item list.")
  10038. self.inform.emit('[ERROR_NOTCL] %s' %
  10039. _("Failed to load recent projects item list."))
  10040. return
  10041. try:
  10042. self.recent_projects = json.load(fp)
  10043. except json.scanner.JSONDecodeError:
  10044. App.log.error("Failed to parse recent project item list.")
  10045. self.inform.emit('[ERROR_NOTCL] %s' %
  10046. _("Failed to parse recent project item list."))
  10047. fp.close()
  10048. return
  10049. fp.close()
  10050. # Closure needed to create callbacks in a loop.
  10051. # Otherwise late binding occurs.
  10052. def make_callback(func, fname):
  10053. def opener():
  10054. func(fname)
  10055. return opener
  10056. def reset_recent_files():
  10057. # Reset menu
  10058. self.ui.recent.clear()
  10059. self.recent = []
  10060. try:
  10061. ff = open(self.data_path + '/recent.json', 'w')
  10062. except IOError:
  10063. App.log.error("Failed to open recent items file for writing.")
  10064. return
  10065. json.dump(self.recent, ff)
  10066. def reset_recent_projects():
  10067. # Reset menu
  10068. self.ui.recent_projects.clear()
  10069. self.recent_projects = []
  10070. try:
  10071. fp = open(self.data_path + '/recent_projects.json', 'w')
  10072. except IOError:
  10073. App.log.error("Failed to open recent projects items file for writing.")
  10074. return
  10075. json.dump(self.recent, fp)
  10076. # Reset menu
  10077. self.ui.recent.clear()
  10078. self.ui.recent_projects.clear()
  10079. # Create menu items for projects
  10080. for recent in self.recent_projects:
  10081. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  10082. if recent['kind'] == 'project':
  10083. try:
  10084. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  10085. # Attach callback
  10086. o = make_callback(openers[recent["kind"]], recent['filename'])
  10087. action.triggered.connect(o)
  10088. self.ui.recent_projects.addAction(action)
  10089. except KeyError:
  10090. App.log.error("Unsupported file type: %s" % recent["kind"])
  10091. # Last action in Recent Files menu is one that Clear the content
  10092. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  10093. (_("Clear Recent projects")), self)
  10094. clear_action_proj.triggered.connect(reset_recent_projects)
  10095. self.ui.recent_projects.addSeparator()
  10096. self.ui.recent_projects.addAction(clear_action_proj)
  10097. # Create menu items for files
  10098. for recent in self.recent:
  10099. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  10100. if recent['kind'] != 'project':
  10101. try:
  10102. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  10103. # Attach callback
  10104. o = make_callback(openers[recent["kind"]], recent['filename'])
  10105. action.triggered.connect(o)
  10106. self.ui.recent.addAction(action)
  10107. except KeyError:
  10108. App.log.error("Unsupported file type: %s" % recent["kind"])
  10109. # Last action in Recent Files menu is one that Clear the content
  10110. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  10111. (_("Clear Recent files")), self)
  10112. clear_action.triggered.connect(reset_recent_files)
  10113. self.ui.recent.addSeparator()
  10114. self.ui.recent.addAction(clear_action)
  10115. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  10116. # self.ui.menufilerecent.set_submenu(recent_menu)
  10117. # recent_menu.show_all()
  10118. # self.ui.recent.show()
  10119. self.log.debug("Recent items list has been populated.")
  10120. def setup_component_editor(self):
  10121. # label = QtWidgets.QLabel("Choose an item from Project")
  10122. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  10123. sel_title = QtWidgets.QTextEdit(
  10124. _('<b>Shortcut Key List</b>'))
  10125. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  10126. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  10127. settings = QSettings("Open Source", "FlatCAM")
  10128. if settings.contains("notebook_font_size"):
  10129. fsize = settings.value('notebook_font_size', type=int)
  10130. else:
  10131. fsize = 12
  10132. tsize = fsize + int(fsize / 2)
  10133. # selected_text = (_('''
  10134. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  10135. #
  10136. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  10137. # The normal flow when working in FlatCAM is the following:</span></p>
  10138. #
  10139. # <ol>
  10140. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  10141. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  10142. # even dragging and dropping the files on the GUI.<br />
  10143. # <br />
  10144. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  10145. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  10146. # &nbsp;</li>
  10147. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  10148. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  10149. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  10150. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  10151. # <br />
  10152. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  10153. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  10154. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  10155. # it even if it was out of focus.<br />
  10156. # <br />
  10157. # You can change the parameters in this screen and the flow direction is like this:<br />
  10158. # <br />
  10159. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  10160. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  10161. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  10162. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  10163. # </ol>
  10164. #
  10165. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  10166. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  10167. # <strong>F3</strong>.</span></p>
  10168. #
  10169. # ''').format(fsize=fsize, tsize=tsize))
  10170. selected_text = '''
  10171. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  10172. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  10173. {s1}</span></p>
  10174. <ol>
  10175. <li><span style="font-size:{fsize}px">{s2}<br />
  10176. <br />
  10177. {s3}</span><br />
  10178. &nbsp;</li>
  10179. <li><span style="font-size:{fsize}px">{s4}<br />
  10180. &nbsp;</li>
  10181. <br />
  10182. <li><span style="font-size:{fsize}px">{s5}<br />
  10183. &nbsp;</li>
  10184. <br />
  10185. <li><span style="font-size:{fsize}px">{s6}<br />
  10186. <br />
  10187. {s7}</span></li>
  10188. </ol>
  10189. <p><span style="font-size:{fsize}px">{s8}</span></p>
  10190. '''.format(
  10191. title=_("Selected Tab - Choose an Item from Project Tab"),
  10192. subtitle=_("Details"),
  10193. s1=_("The normal flow when working in FlatCAM is the following:"),
  10194. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  10195. "using either the toolbars, key shortcuts or even dragging and dropping the "
  10196. "files on the GUI."),
  10197. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  10198. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  10199. "actions offered within the app."),
  10200. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  10201. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  10202. "SELECTED TAB will be updated with the object properties according to its kind: "
  10203. "Gerber, Excellon, Geometry or CNCJob object."),
  10204. s5=_("If the selection of the object is done on the canvas by single click instead, "
  10205. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  10206. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  10207. "the SELECTED TAB and populate it even if it was out of focus."),
  10208. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  10209. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  10210. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  10211. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  10212. "(again, done in SELECTED TAB) --> Save GCode."),
  10213. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  10214. "or through its own key shortcut: <b>F3</b>."),
  10215. tsize=tsize,
  10216. fsize=fsize
  10217. )
  10218. sel_title.setText(selected_text)
  10219. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  10220. self.ui.selected_scroll_area.setWidget(sel_title)
  10221. def setup_obj_classes(self):
  10222. """
  10223. Sets up application specifics on the FlatCAMObj class.
  10224. :return: None
  10225. """
  10226. FlatCAMObj.app = self
  10227. ObjectCollection.app = self
  10228. Gerber.app = self
  10229. Excellon.app = self
  10230. Geometry.app = self
  10231. CNCjob.app = self
  10232. FCProcess.app = self
  10233. FCProcessContainer.app = self
  10234. OptionsGroupUI.app = self
  10235. def version_check(self):
  10236. """
  10237. Checks for the latest version of the program. Alerts the
  10238. user if theirs is outdated. This method is meant to be run
  10239. in a separate thread.
  10240. :return: None
  10241. """
  10242. self.log.debug("version_check()")
  10243. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  10244. full_url = App.version_url + \
  10245. "?s=" + str(self.defaults['global_serial']) + \
  10246. "&v=" + str(self.version) + \
  10247. "&os=" + str(self.os) + \
  10248. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  10249. else:
  10250. # no_stats dict; just so it won't break things on website
  10251. no_ststs_dict = {}
  10252. no_ststs_dict["global_ststs"] = {}
  10253. full_url = App.version_url + \
  10254. "?s=" + str(self.defaults['global_serial']) + \
  10255. "&v=" + str(self.version) + \
  10256. "&os=" + str(self.os) + \
  10257. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  10258. App.log.debug("Checking for updates @ %s" % full_url)
  10259. # ## Get the data
  10260. try:
  10261. f = urllib.request.urlopen(full_url)
  10262. except Exception:
  10263. # App.log.warning("Failed checking for latest version. Could not connect.")
  10264. self.log.warning("Failed checking for latest version. Could not connect.")
  10265. self.inform.emit('[WARNING_NOTCL] %s' %
  10266. _("Failed checking for latest version. Could not connect."))
  10267. return
  10268. try:
  10269. data = json.load(f)
  10270. except Exception as e:
  10271. App.log.error("Could not parse information about latest version.")
  10272. self.inform.emit('[ERROR_NOTCL] %s' %
  10273. _("Could not parse information about latest version."))
  10274. App.log.debug("json.load(): %s" % str(e))
  10275. f.close()
  10276. return
  10277. f.close()
  10278. # ## Latest version?
  10279. if self.version >= data["version"]:
  10280. App.log.debug("FlatCAM is up to date!")
  10281. self.inform.emit('[success] %s' %
  10282. _("FlatCAM is up to date!"))
  10283. return
  10284. App.log.debug("Newer version available.")
  10285. self.message.emit(
  10286. _("Newer Version Available"),
  10287. _("There is a newer version of FlatCAM available for download:\n\n") +
  10288. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  10289. _("info")
  10290. )
  10291. def on_plotcanvas_setup(self, container=None):
  10292. """
  10293. This is doing the setup for the plot area (canvas)
  10294. :param container: widget where to install the canvas
  10295. :return: None
  10296. """
  10297. if container:
  10298. plot_container = container
  10299. else:
  10300. plot_container = self.ui.right_layout
  10301. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  10302. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  10303. self.is_legacy = True
  10304. self.defaults["global_graphic_engine"] = "2D"
  10305. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  10306. else:
  10307. try:
  10308. self.plotcanvas = PlotCanvas(plot_container, self)
  10309. except Exception as er:
  10310. msg_txt = traceback.format_exc()
  10311. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  10312. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  10313. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  10314. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  10315. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  10316. msg += msg_txt
  10317. self.inform.emit(msg)
  10318. return 'fail'
  10319. # So it can receive key presses
  10320. self.plotcanvas.native.setFocus()
  10321. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  10322. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  10323. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  10324. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  10325. # Keys over plot enabled
  10326. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  10327. if self.defaults['global_cursor_type'] == 'small':
  10328. self.app_cursor = self.plotcanvas.new_cursor()
  10329. else:
  10330. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  10331. if self.ui.grid_snap_btn.isChecked():
  10332. self.app_cursor.enabled = True
  10333. else:
  10334. self.app_cursor.enabled = False
  10335. if self.is_legacy is False:
  10336. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  10337. else:
  10338. # will use the default Matplotlib axes
  10339. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  10340. def on_zoom_fit(self, event):
  10341. """
  10342. Callback for zoom-out request. This can be either from the corresponding
  10343. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  10344. with axes limits from the geometry bounds of all objects.
  10345. :param event: Ignored.
  10346. :return: None
  10347. """
  10348. if self.is_legacy is False:
  10349. self.plotcanvas.fit_view()
  10350. else:
  10351. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  10352. width = xmax - xmin
  10353. height = ymax - ymin
  10354. xmin -= 0.05 * width
  10355. xmax += 0.05 * width
  10356. ymin -= 0.05 * height
  10357. ymax += 0.05 * height
  10358. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  10359. def on_zoom_in(self):
  10360. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  10361. def on_zoom_out(self):
  10362. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  10363. def disable_all_plots(self):
  10364. self.report_usage("disable_all_plots()")
  10365. self.disable_plots(self.collection.get_list())
  10366. self.inform.emit('[success] %s' %
  10367. _("All plots disabled."))
  10368. def disable_other_plots(self):
  10369. self.report_usage("disable_other_plots()")
  10370. self.disable_plots(self.collection.get_non_selected())
  10371. self.inform.emit('[success] %s' %
  10372. _("All non selected plots disabled."))
  10373. def enable_all_plots(self):
  10374. self.report_usage("enable_all_plots()")
  10375. self.enable_plots(self.collection.get_list())
  10376. self.inform.emit('[success] %s' %
  10377. _("All plots enabled."))
  10378. def on_enable_sel_plots(self):
  10379. log.debug("App.on_enable_sel_plot()")
  10380. object_list = self.collection.get_selected()
  10381. self.enable_plots(objects=object_list)
  10382. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  10383. def on_disable_sel_plots(self):
  10384. log.debug("App.on_disable_sel_plot()")
  10385. # self.inform.emit(_("Disabling plots ..."))
  10386. object_list = self.collection.get_selected()
  10387. self.disable_plots(objects=object_list)
  10388. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  10389. def enable_plots(self, objects):
  10390. """
  10391. Disables plots
  10392. :param objects: list of Objects to be enabled
  10393. :return:
  10394. """
  10395. log.debug("Enabling plots ...")
  10396. # self.inform.emit(_("Working ..."))
  10397. for obj in objects:
  10398. if obj.options['plot'] is False:
  10399. obj.options.set_change_callback(lambda x: None)
  10400. obj.options['plot'] = True
  10401. try:
  10402. # only the Gerber obj has on_plot_cb_click() method
  10403. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  10404. # disable this cb while disconnected,
  10405. # in case the operation takes time the user is not allowed to change it
  10406. obj.ui.plot_cb.setDisabled(True)
  10407. except AttributeError:
  10408. pass
  10409. obj.set_form_item("plot")
  10410. try:
  10411. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  10412. obj.ui.plot_cb.setDisabled(False)
  10413. except AttributeError:
  10414. pass
  10415. obj.options.set_change_callback(obj.on_options_change)
  10416. def worker_task(objs):
  10417. with self.proc_container.new(_("Enabling plots ...")):
  10418. for obj in objs:
  10419. # obj.options['plot'] = True
  10420. if isinstance(obj, FlatCAMCNCjob):
  10421. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  10422. else:
  10423. obj.plot(visible=True)
  10424. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  10425. # self.plots_updated.emit()
  10426. def disable_plots(self, objects):
  10427. """
  10428. Disables plots
  10429. :param objects: list of Objects to be disabled
  10430. :return:
  10431. """
  10432. # if no objects selected then do nothing
  10433. if not self.collection.get_selected():
  10434. return
  10435. log.debug("Disabling plots ...")
  10436. # self.inform.emit(_("Working ..."))
  10437. for obj in objects:
  10438. if obj.options['plot'] is True:
  10439. obj.options.set_change_callback(lambda x: None)
  10440. obj.options['plot'] = False
  10441. try:
  10442. # only the Gerber obj has on_plot_cb_click() method
  10443. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  10444. obj.ui.plot_cb.setDisabled(True)
  10445. except AttributeError:
  10446. pass
  10447. obj.set_form_item("plot")
  10448. try:
  10449. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  10450. obj.ui.plot_cb.setDisabled(False)
  10451. except AttributeError:
  10452. pass
  10453. obj.options.set_change_callback(obj.on_options_change)
  10454. try:
  10455. self.delete_selection_shape()
  10456. except Exception as e:
  10457. log.debug("App.disable_plots() --> %s" % str(e))
  10458. # self.plots_updated.emit()
  10459. def worker_task(objs):
  10460. with self.proc_container.new(_("Disabling plots ...")):
  10461. for obj in objs:
  10462. # obj.options['plot'] = True
  10463. if isinstance(obj, FlatCAMCNCjob):
  10464. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  10465. else:
  10466. obj.plot(visible=False)
  10467. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  10468. def toggle_plots(self, objects):
  10469. """
  10470. Toggle plots visibility
  10471. :param objects: list of Objects for which to be toggled the visibility
  10472. :return:
  10473. """
  10474. # if no objects selected then do nothing
  10475. if not self.collection.get_selected():
  10476. return
  10477. log.debug("Toggling plots ...")
  10478. self.inform.emit(_("Working ..."))
  10479. for obj in objects:
  10480. if obj.options['plot'] is False:
  10481. obj.options['plot'] = True
  10482. else:
  10483. obj.options['plot'] = False
  10484. self.plots_updated.emit()
  10485. def clear_plots(self):
  10486. objects = self.collection.get_list()
  10487. for obj in objects:
  10488. obj.clear(obj == objects[-1])
  10489. # Clear pool to free memory
  10490. self.clear_pool()
  10491. def on_set_color_action_triggered(self):
  10492. new_color = self.defaults['gerber_plot_fill']
  10493. act_name = self.sender().text()
  10494. sel_obj_list = self.collection.get_selected()
  10495. if not sel_obj_list:
  10496. return
  10497. # a default value, I just chose this one
  10498. alpha_level = 'BF'
  10499. for sel_obj in sel_obj_list:
  10500. if sel_obj.kind == 'excellon':
  10501. alpha_level = str(hex(
  10502. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  10503. elif sel_obj.kind == 'gerber':
  10504. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  10505. elif sel_obj.kind == 'geometry':
  10506. alpha_level = 'FF'
  10507. else:
  10508. log.debug(
  10509. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  10510. continue
  10511. sel_obj.alpha_level = alpha_level
  10512. if act_name == _('Red'):
  10513. new_color = '#FF0000' + alpha_level
  10514. if act_name == _('Blue'):
  10515. new_color = '#0000FF' + alpha_level
  10516. if act_name == _('Yellow'):
  10517. new_color = '#FFDF00' + alpha_level
  10518. if act_name == _('Green'):
  10519. new_color = '#00FF00' + alpha_level
  10520. if act_name == _('Purple'):
  10521. new_color = '#FF00FF' + alpha_level
  10522. if act_name == _('Brown'):
  10523. new_color = '#A52A2A' + alpha_level
  10524. if act_name == _('White'):
  10525. new_color = '#FFFFFF' + alpha_level
  10526. if act_name == _('Black'):
  10527. new_color = '#000000' + alpha_level
  10528. if act_name == _('Custom'):
  10529. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  10530. c_dialog = QtWidgets.QColorDialog()
  10531. plot_fill_color = c_dialog.getColor(initial=new_color)
  10532. if plot_fill_color.isValid() is False:
  10533. return
  10534. new_color = str(plot_fill_color.name()) + alpha_level
  10535. if act_name == _("Default"):
  10536. for sel_obj in sel_obj_list:
  10537. if sel_obj.kind == 'excellon':
  10538. new_color = self.defaults['excellon_plot_fill']
  10539. new_line_color = self.defaults['excellon_plot_line']
  10540. elif sel_obj.kind == 'gerber':
  10541. new_color = self.defaults['gerber_plot_fill']
  10542. new_line_color = self.defaults['gerber_plot_line']
  10543. elif sel_obj.kind == 'geometry':
  10544. new_color = self.defaults['geometry_plot_line']
  10545. new_line_color = self.defaults['geometry_plot_line']
  10546. else:
  10547. log.debug(
  10548. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  10549. continue
  10550. sel_obj.fill_color = new_color
  10551. sel_obj.outline_color = new_line_color
  10552. sel_obj.shapes.redraw(
  10553. update_colors=(new_color, new_line_color)
  10554. )
  10555. return
  10556. if act_name == _("Transparency"):
  10557. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  10558. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  10559. if ok_button:
  10560. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  10561. for sel_obj in sel_obj_list:
  10562. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  10563. sel_obj.shapes.redraw(
  10564. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  10565. )
  10566. return
  10567. new_line_color = color_variant(new_color[:7], 0.7)
  10568. if act_name == _("White"):
  10569. new_line_color = color_variant("#dedede", 0.7)
  10570. for sel_obj in sel_obj_list:
  10571. sel_obj.fill_color = new_color
  10572. sel_obj.outline_color = new_line_color
  10573. sel_obj.shapes.redraw(
  10574. update_colors=(new_color, new_line_color)
  10575. )
  10576. def on_grid_snap_triggered(self, state):
  10577. if state:
  10578. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_filled_16.png'))
  10579. else:
  10580. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_16.png'))
  10581. def generate_cnc_job(self, objects):
  10582. self.report_usage("generate_cnc_job()")
  10583. # for obj in objects:
  10584. # obj.generatecncjob()
  10585. for obj in objects:
  10586. obj.on_generatecnc_button_click()
  10587. def save_project(self, filename, quit_action=False, silent=False):
  10588. """
  10589. Saves the current project to the specified file.
  10590. :param filename: Name of the file in which to save.
  10591. :type filename: str
  10592. :param quit_action: if the project saving will be followed by an app quit; boolean
  10593. :param silent: if True will not display status messages
  10594. :return: None
  10595. """
  10596. self.log.debug("save_project()")
  10597. self.save_in_progress = True
  10598. with self.proc_container.new(_("Saving FlatCAM Project")):
  10599. # Capture the latest changes
  10600. # Current object
  10601. try:
  10602. self.collection.get_active().read_form()
  10603. except Exception as e:
  10604. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  10605. pass
  10606. # Serialize the whole project
  10607. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  10608. "options": self.options,
  10609. "version": self.version}
  10610. if self.defaults["global_save_compressed"] is True:
  10611. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  10612. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  10613. # # Write
  10614. f.write(g)
  10615. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  10616. else:
  10617. # Open file
  10618. try:
  10619. f = open(filename, 'w')
  10620. except IOError:
  10621. App.log.error("Failed to open file for saving: %s", filename)
  10622. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  10623. return
  10624. # Write
  10625. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  10626. f.close()
  10627. # verification of the saved project
  10628. # Open and parse
  10629. try:
  10630. saved_f = open(filename, 'r')
  10631. except IOError:
  10632. if silent is False:
  10633. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10634. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  10635. return
  10636. try:
  10637. saved_d = json.load(saved_f, object_hook=dict2obj)
  10638. except Exception:
  10639. if silent is False:
  10640. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10641. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  10642. f.close()
  10643. return
  10644. saved_f.close()
  10645. if silent is False:
  10646. if 'version' in saved_d:
  10647. self.inform.emit('[success] %s: %s' %
  10648. (_("Project saved to"), filename))
  10649. else:
  10650. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10651. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  10652. tb_settings = QSettings("Open Source", "FlatCAM")
  10653. lock_state = self.ui.lock_action.isChecked()
  10654. tb_settings.setValue('toolbar_lock', lock_state)
  10655. # This will write the setting to the platform specific storage.
  10656. del tb_settings
  10657. # if quit:
  10658. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  10659. # t.start()
  10660. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  10661. def start_delayed_quit(self, delay, filename, should_quit=None):
  10662. """
  10663. :param delay: period of checking if project file size is more than zero; in seconds
  10664. :param filename: the name of the project file to be checked periodically for size more than zero
  10665. :param should_quit: if the task finished will be followed by an app quit; boolean
  10666. :return:
  10667. """
  10668. to_quit = should_quit
  10669. self.save_timer = QtCore.QTimer()
  10670. self.save_timer.setInterval(delay)
  10671. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  10672. self.save_timer.start()
  10673. def check_project_file_size(self, filename, should_quit=None):
  10674. """
  10675. :param filename: the name of the project file to be checked periodically for size more than zero
  10676. :param should_quit: will quit the app if True; boolean
  10677. :return:
  10678. """
  10679. try:
  10680. if os.stat(filename).st_size > 0:
  10681. self.save_in_progress = False
  10682. self.save_timer.stop()
  10683. if should_quit:
  10684. self.app_quit.emit()
  10685. except Exception:
  10686. traceback.print_exc()
  10687. def on_plotarea_tab_closed(self, tab_idx):
  10688. widget = self.ui.plot_tab_area.widget(tab_idx)
  10689. if widget is not None:
  10690. widget.deleteLater()
  10691. self.ui.plot_tab_area.removeTab(tab_idx)
  10692. def on_options_app2project(self):
  10693. """
  10694. Callback for Options->Transfer Options->App=>Project. Copies options
  10695. from application defaults to project defaults.
  10696. :return: None
  10697. """
  10698. self.report_usage("on_options_app2project")
  10699. self.defaults_read_form()
  10700. self.options.update(self.defaults)
  10701. # self.options_write_form()
  10702. class ArgsThread(QtCore.QObject):
  10703. open_signal = pyqtSignal(list)
  10704. start = pyqtSignal()
  10705. if sys.platform == 'win32':
  10706. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  10707. else:
  10708. address = ('/tmp/testipc', 'AF_UNIX')
  10709. def __init__(self):
  10710. super(ArgsThread, self).__init__()
  10711. self.listener = None
  10712. self.start.connect(self.run)
  10713. def my_loop(self, address):
  10714. try:
  10715. self.listener = Listener(*address)
  10716. while True:
  10717. conn = self.listener.accept()
  10718. self.serve(conn)
  10719. except socket.error:
  10720. conn = Client(*address)
  10721. conn.send(sys.argv)
  10722. conn.send('close')
  10723. # close the current instance only if there are args
  10724. if len(sys.argv) > 1:
  10725. try:
  10726. self.listener.close()
  10727. except Exception:
  10728. pass
  10729. sys.exit()
  10730. def serve(self, conn):
  10731. while True:
  10732. msg = conn.recv()
  10733. if msg == 'close':
  10734. break
  10735. self.open_signal.emit(msg)
  10736. conn.close()
  10737. # the decorator is a must; without it this technique will not work unless the start signal is connected
  10738. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  10739. @pyqtSlot()
  10740. def run(self):
  10741. self.my_loop(self.address)
  10742. class GracefulException(Exception):
  10743. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  10744. def __init__(self):
  10745. super().__init__()
  10746. def __str__(self):
  10747. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  10748. # end of file