FlatCAMApp.py 320 KB

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